为什么在C 中超载邮政增量运算符两次调用构造函数
Why does overloading the post increment operator in C++ call the constructor twice?
我正在玩重载不同的操作员,并添加了打印语句以观察发生的事情。当我超载帖子增量运算符时,我看到构造函数被称为两次,但我不明白为什么。
#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 30n";
this->value++;
return this->value;
}
};
int main() {
cout << "DEBUG 10n";
ChildClass child(0);
cout << "value initial = " << child.getValue() << endl;
cout << "DEBUG 20n";
child++;
cout << "DEBUG 40n";
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;
说返回 int
但是方法原型是
ChildClass operator++( int )
因此,编译器认为,获得int
需要ChildClass
-让我们从int
构造一个。因此输出
相关文章:
- 用相同的参数声明两个构造函数的最偶像化的方法是什么?
- pair的两个构造函数几乎相同,为什么不生成构建错误?
- 为什么<T> LLVM 中的预期为 Expect&&... 实现两个构造函数<T>?
- 为什么我的类只适用于两个构造函数 C++
- 两个构造函数(带和不带参数),没有输入 -> 没有参数运行。跳过上述类中的构造函数
- 类介绍 (c++) 项目希望我们创建两个构造函数,但它们都不需要任何参数 - 我应该在这里做什么?
- 除了两个构造函数外,C++库导入也可以工作
- 两次构造对象
- 在两个构造函数之前将我的静态数据成员在 CPP 文件中初始化为 0
- 如何有条件地在具有相同签名的两个构造函数之间切换
- RAII 在两个构造函数之间进行选择的方式
- 调用对数组引用两次的函数
- std::make_shared在VS2012中进行了两次构造函数调用
- 具有两个构造函数的抽象类
- 如何在c++中实现二次构造函数
- 这两个构造函数调用之间的区别
- 为什么在我的程序中调用两个构造函数
- 组合复制和移动的两个构造函数
- 为什么这两个构造函数一起不会产生歧义错误?
- C++两次传递函数指针导致问题