我正在尝试使用以下行重载 += 运算符:
a = b += c += 100.01;
但是我在该代码中的第二个 += 显示错误,因为我猜它不匹配任何实现?
这是我的完整相关代码:
主要.cpp:
#include <iostream>
#include "Account.h"
using namespace sict;
void displayABC(const Account& a, const Account& b, const Account& c)
{
std::cout << "A: " << a << std::endl << "B: " << b << std::endl
<< "C: " << c << std::endl << "--------" << std::endl;
}
int main()
{
Account a("No Name");
Account b("Saving", 10000.99);
Account c("Checking", 100.99);
displayABC(a, b, c);
a = b + c;
displayABC(a, b, c);
a = "Joint";
displayABC(a, b, c);
a = b += c;
displayABC(a, b, c);
a = b += c += 100.01;
displayABC(a, b, c);
return 0;
}
Account.h(相关定义)
class Account{
public:
friend Account operator+(const Account &p1, const Account &p2);
Account& operator+=(Account& s1);
Account & operator=(const char name[]);
friend double & operator+=(double & Q, Account & A);
Account & operator=(Account D);
};
Account operator+(const Account &p1, const Account &p2);
double operator+=(double& d, const Account& a);
};
Account.cpp(相关实现)
Account& Account::operator+=(Account &s1) {
double b = this->balance_ + s1.balance_;
this->balance_ = b;
return *this;
}
Account & Account::operator=(Account D) {
strcpy(name_, D.name_ );
this->balance_ = D.balance_;
return *this;
}
Account & Account::operator=(const char name[])
{
strcpy_s(name_, name);
return *this;
}
double & operator+=(double & Q, Account & A)
{
Q = Q + A.balance_;
return Q;
}
所以我的问题是,如何正确更改我的实现以运行此函数:a = b += c += 100.01;
谢谢。
最佳答案
在这个声明中
a = b += c += 100.01;
在第一个表达式
c += 100.01
被评估。但是该类没有相应的重载运算符。
另一方面,如果该类具有将 double 类型的对象转换为 Account 类型的转换构造函数,那么相应的 operatpr +=
应该声明为
Account& operator+=(const Account& s1);
^^^^^
还要考虑到这些声明
friend double & operator+=(double & Q, Account & A);
和
double operator+=(double& d, const Account& a);
不同。
关于C++ - 重载 += 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35920325/