我正在玩重载不同的操作符并添加打印语句来观察正在发生的事情。当我重载post增量运算符时,我看到构造函数被调用了两次,但我不明白为什么。
#include <iostream>
using namespace std;
class ParentClass {
public:
ParentClass() {
cout << "In ParentClass!" << endl;
}
};
class ChildClass : public ParentClass {
public:
int value;
ChildClass() { }
ChildClass(int a)
: value(a) {
cout << "In ChildClass!" << endl;
}
int getValue() { return value; }
ChildClass operator++( int ) {
cout << "DEBUG 30\n";
this->value++;
return this->value;
}
};
int main() {
cout << "DEBUG 10\n";
ChildClass child(0);
cout << "value initial = " << child.getValue() << endl;
cout << "DEBUG 20\n";
child++;
cout << "DEBUG 40\n";
cout << "value incremented = " << child.getValue() << endl;
}
运行此代码后的输出是:
DEBUG 10
In ParentClass!
In ChildClass!
value initial = 0
DEBUG 20
DEBUG 30
In ParentClass!
In ChildClass!
DEBUG 40
value incremented = 1
答案 0 :(得分:1)
本声明
return this->value;
表示返回int
但方法原型是
ChildClass operator++( int )
所以编译器认为,int
需要一个ChildClass
- 让我们从int
构造一个。因此输出