class - C++ Overload: [Error] no match for 'operator=' (operand types are 'String' and 'String') -
this question has answer here:
i learning c++ studying visual c++ textbook.
when want overload operator+, code i've used overloading operator= went wrong.
#include <iostream> #include <string.h> using namespace std; //this demo shows how default operator may cause conflict, use overloaded operator instead class string{ private: char* string; int len; public: string(const char*); string(); ~string(){delete [] string;} string& operator=(string&); //in book used //string & operator=(string&) went wrong //string object returned + got value, not initiated object string operator+(string&); //opreator + void show_string(){ cout << "string: " << string << " \tstring address: " << (void*)string << " \tlength: " << len << endl; } }; string::string():len(0){ //constructor no argument string = new char[len+1]; string[0] = '\0'; } string::string(const char* i_string):len(strlen(i_string)){ //constructor string = new char[len+1]; strcpy(string,i_string); } string& string::operator=(string& str_ref){ //overloading operator = //the function reference , return delete [] string; cout << "overloading operator =...\n"; len = str_ref.len; string = new char[len+1]; strcpy(string,str_ref.string); return *this; } string string::operator+(string& str){ cout << "overloading operator +...\n"; char* strbuf = new char[len+str.len+1]; strcpy(strbuf,string); strcat(strbuf,str.string); string retstr(strbuf); delete [] strbuf; return retstr; //call value coz made new string } int main(){ string a_string("my "); string b_string("string"),c_string; cout << "show (a_string+b_string)...\n"; (a_string+b_string).show_string(); c_string = a_string + b_string; cout << "show c_string...\n"; c_string.show_string(); return 0; }
it's strange because did when use operator+ or operator= individually.
string a_string("apple"); string b_string; b_string = a_string; (a_string+b_string).show_string();
here's error
in function 'int main()': 56:11: error: no match 'operator=' (operand types 'string' , 'string') c_string = a_string + b_string; ^ note: candidate is: note: string& string::operator=(string&) string& string::operator=(string& str_ref){ \\overloading operator = ^ note: no known conversion argument 1 'string' 'string&'
i thought can use string argument string&, told in book.
changed argument of operator= string, , works.
string& operator=(string&);
to
string& operator=(string);
now confused when use reference or string only.
in statement
c_string = a_string + b_string;
there created temporary object of type string
result of executing operator
string operator+(string&);
you may not bind non-constant lvalue reference temporary object.
either rewrite/add assignment operator like
string& operator=( const string&); ^^^^
or add move assignment operator.
string& operator=( string &&); ^^
Comments
Post a Comment