【发布时间】:2018-05-09 01:28:29
【问题描述】:
我正在玩重载不同的运算符并添加打印语句来观察发生了什么。当我重载后自增运算符时,我看到构造函数被调用了两次,但我不明白为什么。
#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
【问题讨论】:
-
请注意,代码重载了 post-increment 运算符,但实现了 pre-increment。
-
@PeteBecker 也许我错过了一些东西。我以为在operator++(int)中添加参数'int'实现了后自增?
-
代码返回增量值。这就是预增量的作用。后增量应返回原始值。
-
@PeteBecker 您说得对,先生!我在想必须返回增加的值,但现在我意识到它只需要增加来模拟整数的行为。
标签: c++ constructor operator-overloading post-increment