![](/img/trans.png)
[英]Overloaded `!=` operator in custom iterator class is not working properly
[英]Overloaded Operator not working properly?
我在編譯程序時遇到錯誤,不確定如何使用適當的函數來解決該問題,以解決此問題。 我將在下面發布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
一個:聯合:$ 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.