class mystring {
private:
string s;
public:
mystring(string ss) {
cout << "mystring : mystring() : " + s <<endl;
s = ss;
}
/*! mystring& operator=(const string ss) {
cout << "mystring : mystring& operator=(string) : " + s <<endl;
s = ss;
//! return this;
return (mystring&)this; // why COMPILE ERROR
} */
mystring operator=(const string ss) {
cout << "mystring : mystring operator=(string) : " + s <<endl;
s = ss;
return *this;
}
mystring operator=(const char ss[]) {
cout << "mystring : mystring operator=(char[]) : " << ss <<endl;
s = ss;
return *this;
}
};
mystring str1 = "abc"; // why COMPILE ERROR
mystring *str2 = new mystring("bcd");
So the questiones are
how to make a correct mystring& opeartor= overload?That is,how could I return a reference rather than a pointer?(could we tranfer between reference and pointer in C++?)
how to make a correct mystring operator= overload?I thought the source code would work fine,but it turns out I still could not assign const char[] to mystring as if I didn't overload the operator=.
thanks.
What you need is a 'conversion' constructor that takes a const char*
:
mystring( char const* ss) {
cout << "mystring : mystring(char*) ctor : " << ss <<endl;
s = ss;
}
The line you're having a problem with:
mystring str1 = "abc"; // why COMPILE ERROR
isn't really an assignment - it's an initializer.
mystring& operator=(const string &ss)
{
cout << "mystring : mystring operator=(string) : " + s <<endl;
s = ss;
return *this; // return the reference to LHS object.
}
As others pointed out, "string"
has const char *
type and you should overload assignment operator for it.
mystring& operator=(const char * s);
To get a reference from a pointer *this
is suffice, no need to cast anything.
mystring& operator=(const string& ss) {
cout << "mystring : mystring operator=(string) : " << s << endl;
s = ss;
return *this;
}
mystring& operator=(const char* const pStr) {
cout << "mystring : mystring operator=(zzzz) : " << pStr << endl;
s = pStr;
return *this;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.