im trying to Set the name of A to "new name" and return the reference of A however im getting an error from the operator= function 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. If i simply do return n = "new name"; it returns a segmentation fault
Please pay attention to my operator= function in my Account.cpp file.
Here are my three files:
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; } Here is my Account.cpp i removed functions that i thought were unnecessary. Edit: I'll include my entire account.cpp and account.h
Account.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); } } Here is the Declaration for the Operator= in Account.h
#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 Any help/tips would be appreciated thanks.
Edit: Added some code to operator=
strncpyagain, like you did before?