C++ 为什么在C++;调用构造函数两次?
我在玩重载不同运算符的游戏,并添加打印语句来观察发生了什么。当我重载后增量操作符时,我看到构造函数被调用了两次,但我不明白为什么C++ 为什么在C++;调用构造函数两次?,c++,constructor,operator-overloading,post-increment,C++,Constructor,Operator Overloading,Post Increment,我在玩重载不同运算符的游戏,并添加打印语句来观察发生了什么。当我重载后增量操作符时,我看到构造函数被调用了两次,但我不明白为什么 #include <iostream> using namespace std; class ParentClass { public: ParentClass() { cout << "In ParentClass!" << endl; } }; class ChildClass : p
#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;
}
此声明
return this->value;
表示返回int
但这种方法是原型的
ChildClass operator++( int )
因此编译器认为,得到一个
int
需要一个ChildClass
——让我们从int
构造一个。因此,输出I遵循一个二进制运算符的示例,其中返回一个带有结果的新类型。我删除了return语句,实际上构造函数只调用了一次。还可以将返回类型更改为int。谢谢@yamex5拥有ChildClass
的++
返回int
对于任何期望操作符+++
的正常行为的人来说都是一个非常令人讨厌的惊喜。有关运算符重载的详细说明,请参阅。@user4581301-它没有返回int
。看看原型和我的解释,我知道。我警告yamex,他们在评论末尾概述的操作过程是个坏主意。请注意,代码重载了后增量运算符,但实现了预增量。@PeteBecker也许我遗漏了什么。我认为在操作符++(int)中添加参数“int”可以实现后增量?代码返回增量值。这就是pre-increment所做的。后增量应返回原始值。@PeteBecker您是对的,先生!我原以为递增的值必须返回,但现在我意识到它只需要递增来模拟整数的行为。
ChildClass operator++( int )