编译程序时出现错误,并且不确定如何使用适当的函数来解决此问题,以解决此问题。我将在下面发布Main,Header和CPP文件,并附上所需的结果。任何帮助/提示,​​不胜感激,谢谢!

错误我得到:

Error   C2679   binary '+=': no operator found which takes a right-hand operand of type 'double'


更新:
我已经修复了更新“ =”运算符重载的代码,除了1行输出外,它都在工作。

这是我得到的输出:

A:没有名字:$ 0.00

B:节省:$ 10000.99

C:支票:$ 100.99



A:没有名字:$ 10101.98

B:节省:$ 10000.99

C:支票:$ 100.99



A:联合:$ 0.00

B:节省:$ 10000.99

C:支票:$ 100.99



A:节省:$ 10101.98

B:节省:$ 10101.98

C:支票:$ 100.99



A:节省:$ 10302.98

B:节省:$ 10302.98

C:支票:$ 201.00



由于某些原因,“ JOINT”余额变为0,我不确定为什么。它应该显示为$ 10101.98

主要的:

#include <iostream>
#include "Account.h"
using namespace std;
void displayABC(const Account& A,
    const Account& B,
    const Account& C) {
    cout << "A: " << A << endl << "B: " << B << endl
            << "C: " << C << endl << "--------" << endl;
}
int main() {
    Account A;
    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;
}


源文件:

#include <iomanip>
#include <cstring>
#include "Account.h"
using namespace std;

    Account::Account() {
            name_[0] = 0;
            balance_ = 0;
    }
    Account::Account(double balance) {
            name_[0] = 0;
            balance_ = balance;
    }
    Account::Account(const char name[], double balance) {
            strncpy(name_, name, 40);
            name_[40] = 0;
            balance_ = balance;
    }


    void Account::display(bool gotoNewline)const {
            cout << (name_[0] ? name_ : "No Name") << ": $" << setprecision(2) << fixed << balance_;
            if (gotoNewline) cout << endl;
    }

    Account& Account::operator+=(Account& other) {

            balance_ += other.balance_;
            return *this;
    }

    Account& Account::operator=(const Account& ls) {

                    strcpy(name_, ls.name_);

            balance_ = ls.balance_;

            return *this;
     }
     Account operator+(const Account &one, const Account &two) {
            return Account(one.balance_ + two.balance_);
    }

    ostream& operator<<(ostream& os, const Account& A) {
            A.display();
            return os;
    }


头文件:

#ifndef _ACCOUNT_H__
#define _ACCOUNT_H__
#include <iostream>

    class Account {
            char name_[41];
            double balance_;
    public:
            Account();
            Account(double balance);
            Account(const char name[], double balance = 0.0);
            void display(bool gotoNewline = true)const;

            Account& operator+=(Account& other);
            Account& operator=(const Account & other);
            friend Account operator+(const Account &one, const Account    &two);



    };

    std::ostream& operator<<(std::ostream& os, const Account& A);
};

#endif

最佳答案

+=运算符方法更改为:

Account& operator+=(const Account& other);

10-07 19:25