【发布时间】:2016-02-05 07:04:52
【问题描述】:
我正在尝试将 A 的名称设置为“新名称”并返回 A 的引用
但是我从 operator= 函数 binary '=' : no operator found which takes a right-hand operand of type 'const char [6]' (or there is no acceptable conversion) 得到一个错误
expression must be a modifiable value.
如果我只是做return n = "new name"; 它会返回一个分段错误
请注意我的 Account.cpp 文件中的 operator= 函数。
这是我的三个文件:
main.cpp:
#include <iostream>
#include "Account.h"
using namespace sict;
using namespace std;
int main(){
Account A;
Account B("Saving", 10000.99);
Account C("Checking", 100.99);
double value = 0;
cout << A << endl << B << endl << C << endl << "--------" << endl;
A = B + C;
A = "Joint";
cout << A << endl << B << endl << C << endl << "--------" << endl;
A = B += C;
cout << A << endl << B << endl << C << endl << "--------" << endl;
value += A;
value += B;
value += C;
cout << "Total balance: " << value << endl;
return 0;
}
这是我的 Account.cpp,我删除了我认为不必要的功能。 编辑:我将包括我的整个 account.cpp 和 account.h
帐户.cpp:
#include "cstring"
#include "iomanip"
#include "Account.h"
using namespace std;
namespace sict{
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()const{
cout << _name << ": $" << setprecision(2) << fixed << _balance;
}
Account& Account::operator+=(Account &s1) {
// return Account(_balance += s1._balance);
_balance += s1._balance;
return *this;
}
Account& Account::operator=( Account& n) const {
strncpy(n._name , n, 40);
return n;
}
double operator+=(double& d, const Account& a){
d += a;
return d;
}
ostream& operator<<(ostream& os, const Account& A){
A.display();
return os;
}
Account operator+(const Account &p1, const Account &p2){
return Account(p1._balance + p2._balance);
}
}
这是 Account.h 中 Operator= 的声明
#ifndef SICT_ACCOUNT_H__
#define SICT_ACCOUNT_H__
#include <iostream>
namespace sict{
class Account{
char _name[41];
double _balance;
public:
Account();
Account(const char name[], double balance = 0.0);
Account(double balance);
void display()const;
friend Account operator+(const Account &p1, const Account &p2);
Account& operator+=(Account& s1) ;
Account& operator=( Account& n) const;
};
Account operator+(const Account &p1, const Account &p2);
double operator+=(double& d, const Account& a);
std::ostream& operator<<(std::ostream& os, const Account& C);
};
#endif
任何帮助/提示将不胜感激。
编辑:在 operator= 中添加了一些代码
【问题讨论】:
-
你遇到了什么错误?
-
@cad,我在上面列出了错误。
-
你为什么不像以前那样再次使用
strncpy? -
你能把文字复制到 strncpy 中吗?如 strncpy(n._name , "新名称", 40); ?
-
在您的编辑中,您切换了 strncpy 函数的前两个操作数。您是否查看了我在下面引用的 strncpy 的引用?
标签: c++ function operator-keyword