gpt4 book ai didi

c++ - 为什么operator '='不能匹配?

转载 作者:行者123 更新时间:2023-11-30 04:15:05 24 4
gpt4 key购买 nike

我经常遇到编译错误:

no match for ‘operator=’ in ‘bObj1 = Balance::operator+(Balance&)(((Balance&)(& bObj2)))’

谁能帮忙指出原因吗?提前致谢。

代码:

class Balance
{
public:
Balance (int b = 0) {balance = b;};
Balance (Balance &);

Balance & operator= (Balance &);
Balance operator+ (Balance &);

int get() {return balance;};
void set(int b) {balance = b;};

private:
int balance;
};

Balance & Balance::operator=(Balance &copy)
{
balance = copy.get();
return *this;
}

Balance Balance::operator+ (Balance &rig)
{
Balance add;
add.set(this->get() + rig.get());
return add;
}

int main()
{
Balance bObj1, bObj2(100);
bObj1 = bObj2;
bObj1 = bObj1 + bObj2; // This line cause the error.
return 0;
}

最佳答案

您的赋值运算符是错误的。您可以安全地删除它,因为隐式运算符对于您的简单类来说已经足够了。阅读When do I need to write an assignment operator?了解更多详情。

class Balance
{
public:
Balance (int b = 0) {balance = b;};
Balance operator+ (const Balance &);

int get() const {return balance;};
void set(int b) {balance = b;};

private:
int balance;
};

Balance Balance::operator+ (const Balance &rig)
{
Balance add;
add.set(this->get() + rig.get());
return add;
}

关于c++ - 为什么operator '='不能匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18565199/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com