为什么在 C++ 中重载 post 增量运算符会调用构造函数两次?
Why does overloading the post increment operator in C++ call the constructor twice?
我正在尝试重载不同的运算符并添加打印语句来观察发生了什么。当我重载 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
这条语句
return this->value;
说 return int
但是方法原型是
ChildClass operator++( int )
所以编译器认为,得到一个 int
需要一个 ChildClass
- 让我们从 int
构造一个。因此输出
我正在尝试重载不同的运算符并添加打印语句来观察发生了什么。当我重载 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
这条语句
return this->value;
说 return int
但是方法原型是
ChildClass operator++( int )
所以编译器认为,得到一个 int
需要一个 ChildClass
- 让我们从 int
构造一个。因此输出