#include <bits/stdc++.h>
using namespace std;
class vec{
public:
int x;
int y;
vec(int a, int b)
{
x = a; y = b;
}
vec operator+(vec that)
{
vec ans(0, 0);
ans.x = this->x + that.x;
ans.y = this->y + that.y;
return ans;
}
};
int main()
{
vec a(0, 1);
a = a + vec(2, 3); // how does this line work
printf("%d %d\n", a.x, a.y);
return 0;
}
每个人都说构造函数不返回任何东西。看起来它正在返回一个对象。我尝试查找临时或未命名的对象,但找不到任何特定于此类表达式的东西。
构造函数是一个特殊的函数,用于初始化内存中的对象。该对象可能在堆栈或堆上。调用构造函数将初始化内存。请注意,构造函数是c ++语法糖。
vec x(0, 1); // creates the object named x of type vec on the stack
vec *px = new vec(2, 3); // creates the object pointed by px on the heap
x = x + vec(2, 3); // vec(2, 3) creates a temporary object on stack
// and initializes it with the parameters.
// The overloaded operator+ on the object x is called,
// passing the temporary object as the formal parameter
// 'that' of operator+ and it returns a temporary object
// on the stack that is copied back into the variable x
// as a result of the = assignment operation
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句