繁体   English   中英

C ++-重载+ =运算符

[英]C++ - Overloaded += Operators

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

a = b += c += 100.01;

但是我在该代码中的第二个+ =显示错误,因为我猜它没有实现?

这是我完整的相关代码:

main.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);

不同。

暂无
暂无

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

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