怎么std::string载的分配运营商?
-
21-09-2019 - |
题
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");
所以questiones是
如何做一个正确的mystring&opeartor=载?就是说,我怎么可能返回参考,而不是指?(我们可以转院之间的参考和指针在C++?)
如何做一个正确的mystring员=载?我思想的源代码的工作的现,但是事实证明我仍然不能分配const char[]为mystring如果我没有超负荷运营商=.
谢谢。
解决方案
什么你需要的是一个'转变'的构造,需要一个 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;
}
- 我加入'&'你串使它 返回的一个参照'这个',而不 它的一个副本(这是很好的做法 这样做,为的输入参数太 你再不uneccessarily做 拷贝输入string),
- 我换一个'+'到'<<'在2号线
- 我改变了你的阵列 const char const*指针
不隶属于 StackOverflow