【发布时间】:2018-11-17 02:06:32
【问题描述】:
有人能解释一下为什么在创建 temp 之后的重载函数中, temp.x 变成 2,而 temp.y 变成 1 吗?默认构造函数没有参数,因此 temp.x 和 temp.y 不应为 0 或具有奇怪的数字?
谢谢!
// overloading operators example
#include <iostream>
using namespace std;
class CVector {
public:
int x,y;
CVector () {};
CVector (int a,int b) : x(a), y(b) {}
CVector operator + (const CVector&);
};
CVector CVector::operator+ (const CVector& param) {
CVector temp;
cout << " x: -> " << temp.x << " <-";
cout << " y: -> " << temp.y << " <-\n";
temp.x = x + param.x;
temp.y = y + param.y;
return temp;
}
int main () {
CVector foo (3,1);
CVector bar (1,2);
CVector result;
result = foo + bar;
cout << result.x << ',' << result.y << '\n';
return 0;
}
Result: x:-> 2 <- y: -> 1 <-
4,3
【问题讨论】:
标签: c++ class constructor overloading default