![](/img/trans.png)
[英]Why does it not work to overload “operator <<” on std::string?
[英]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");
所以问题是
如何创建正确的mystring&opeartor =重载?也就是说,我该如何返回引用而不是指针?(我们可以在C ++中在引用和指针之间转换吗?)
我以为源代码可以正常工作,但事实证明我仍然无法为const char []分配mystring,就像我没有重载operator =一样。
谢谢。
您需要的是一个带有const char*
的“转换”构造const char*
:
mystring( char const* ss) {
cout << "mystring : mystring(char*) ctor : " << ss <<endl;
s = ss;
}
您遇到的问题所在的行:
mystring str1 = "abc"; // why COMPILE ERROR
并不是真正的任务,它是一个初始化程序。
mystring& operator=(const string &ss)
{
cout << "mystring : mystring operator=(string) : " + s <<endl;
s = ss;
return *this; // return the reference to LHS object.
}
正如其他人指出的那样, "string"
具有const char *
类型,您应该为其重载赋值运算符。
mystring& operator=(const char * s);
要从指针获取引用*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.