C++ - 重载 += 运算符

标签 c++ class operator-overloading operators

我正在尝试使用以下行重载 += 运算符:

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/

相关文章:

java - 将内存中的类日志重定向到 ObjectOutputStream

php - 如何从另一个非命名空间类访问不同命名空间中的类

c++ - 重载比较运算符 == C++

c++ - bigint 运算符重载

c++ - 在 VS2017 中搜索内存

c++ - 如何在工厂中为延迟实例化指定具体类/如何延迟构造函数调用

c++ - 范围界定错误并且不能有 cv 限定符?

c++ - 错误 C4716 : must return a value, 由实际返回值的函数抛出

c++ - 将迭代器转换为 int

c++ - 在 C++ 中,可以让类成员成为传入引用吗?