为什么在C 中超载邮政增量运算符两次调用构造函数

Why does overloading the post increment operator in C++ call the constructor twice?

本文关键字:两次 构造函数 调用 运算符 中超 超载 为什么      更新时间:2023-10-16

我正在玩重载不同的操作员,并添加了打印语句以观察发生的事情。当我超载帖子增量运算符时,我看到构造函数被称为两次,但我不明白为什么。

#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构造一个。因此输出