【发布时间】:2020-05-31 14:10:57
【问题描述】:
这是 main.cpp:
int main() {
Person arr[2] = {
Person(18,180),
Person(20,173)
};
arr[0]+arr[1];
return 0;
}
这是 Person.h:
class Person
{
private:
int age;
int height;
public:
Person(int age=20,int height=180);
~Person();
void operator+(Person);
};
这是 Person.cpp:
Person::Person(int age,int height) {
(*this).age = age;
(*this).height = height;
cout << "I'm born.\n";
}
Person::~Person() {
cout << "I'm dead.\n";
}
void Person::operator+(Person a) {
Person result;
result.age = (*this).age + a.age;
result.height = (*this).height + a.height;
cout << result.age << endl;
cout << result.height << endl;
}
为什么这个程序的结果是3个“出生”?4个死了? 初始化对象数组'arr'的过程是什么?
【问题讨论】:
-
result.age = (*this).age + a.age;-->result.age = age + a.age;。你只是用显式的this取消引用来混淆你的代码(在任何情况下,this->age会更好)。(*this).age只是 odd。 -
默认的复制构造函数不提供“我是复制而生的。\n”反馈。
标签: c++ class destructor copy-constructor construct