【问题标题】:Why does overloading the post increment operator in C++ call the constructor twice?为什么在 C++ 中重载后自增运算符会调用两次构造函数?
【发布时间】: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


【解决方案1】:

此声明

  return this->value; 

说返回int

但是方法原型是

 ChildClass operator++( int ) 

所以编译器认为,得到一个int 需要一个ChildClass - 让我们从int 构造一个。因此输出

【讨论】:

  • 我正在关注二元运算符的示例,其中返回了带有结果的新类型。我删除了 return 语句,确实调用了构造函数,但现在调用了一次。并且还将返回类型更改为 int 有效。谢谢!
  • @yamex5 ,拥有ChildClass++ 返回int 对于任何期待operator++ 的正常行为的人来说都是一个非常令人讨厌的惊喜。请参阅What are the basic rules and idioms for operator overloading?,了解有关运算符重载的大量文章。
  • @user4581301 - 它没有返回int。查看原型和我的解释
  • 我知道。我警告 yamex,他们在评论末尾概述的行动方案是个坏主意。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-16
  • 1970-01-01
  • 1970-01-01
  • 2011-05-21
  • 1970-01-01
  • 2013-03-26
  • 1970-01-01
相关资源
最近更新 更多