[英]How does std::string overload the assignment operator?
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++?) 如何创建正确的mystring&opeartor =重载?也就是说,我该如何返回引用而不是指针?(我们可以在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=. 我以为源代码可以正常工作,但事实证明我仍然无法为const char []分配mystring,就像我没有重载operator =一样。
thanks. 谢谢。
What you need is a 'conversion' constructor that takes a const char*
: 您需要的是一个带有const char*
的“转换”构造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. 正如其他人指出的那样, "string"
具有const char *
类型,您应该为其重载赋值运算符。
mystring& operator=(const char * s);
To get a reference from a pointer *this
is suffice, no need to cast anything. 要从指针获取引用*this
已足够,无需强制转换任何内容。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.