简体   繁体   English

重载运算符+构造函数问题

[英]overloading operator+ constructor issue

I am learning C++ from a book and I find references and operator overloading really difficult.我正在从一本书中学习 C++,我发现引用和运算符重载真的很困难。 While studying operator overloading, I can't understand why this program won't work without a constructor that takes an integer as a parameter.在研究运算符重载时,我不明白为什么这个程序在没有将整数作为参数的构造函数的情况下无法运行。

#include <iostream>
using namespace std;

class counter {
public:
    counter();
    counter(int value);
    ~counter();
    int getValue() const { return itsValue;  }
    int setValue(int value) { itsValue = value;  }
    counter operator+(const counter&);
private:
    int itsValue;
};
counter::counter() :
    itsValue(0)
{}
counter::counter(int value) :
    itsValue(value)
{}
counter counter::operator+(const counter& rhs) {
    return itsValue + rhs.getValue();
}
int main()
{
    std::cout << "Hello World!\n";
}

I can't understand why the program won't work in the absence of these lines:我不明白为什么程序在没有这些行的情况下无法运行:

counter(int value);

AND

counter::counter(int value) :
        itsValue(value)
    {}

If you don't have this constructor:如果你没有这个构造函数:

counter(int value);

then you can't do things like:那么你不能做这样的事情:

int n = 3;
counter c = counter{n};
counter c = counter{1};
counter c = 2;
// etc ...

The issue with your operator+ is that you are doing exactly that when you convert the int value itsValue + rhs.getValue() to a counter which is the return type:您的operator+的问题在于,当您将intitsValue + rhs.getValue()转换为作为返回类型的counter时,您正在这样做:

counter counter::operator+(const counter& rhs) {
  return itsValue + rhs.getValue();
}

Without the appropriate constructor, there is no way to construct a counter from an int , and you get an error.如果没有合适的构造函数,就无法从int构造counter ,并且会出现错误。


You can choose not to provide an int constructor, by manually constructing a counter object, and returning that:您可以选择不提供int构造函数,方法是手动构造一个counter对象,然后返回:

counter counter::operator+(const counter& rhs) const {
    counter c;
    c.itsValue = itsValue + rhs.getValue();
    return c;
}

Note that operator+ should be const -qualified.请注意, operator+应该是const限定的。

Here's a demo .这是一个演示


A few other fixes: setValue should return void .其他一些修复: setValue应该返回void You haven't defined the destructor, but you have provided a declaration.您尚未定义析构函数,但已提供声明。 Just remove the declaration, since the implicitly generated destructor is sufficient.只需删除声明,因为隐式生成的析构函数就足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM