std::string 如何重载赋值运算符?
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& operator=重载?也就是说,我怎样才能返回一个引用而不是一个指针?(我们可以在C++中在引用和指针之间转换吗?)
如何做出正确的mystringoperator=重载?我认为源代码可以工作很好,但事实证明我仍然无法将 const char[] 分配给 mystring,就好像我没有重载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++?)
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要的是一个采用 const char* 的“转换”构造函数:
您遇到问题的行:
并不是真正的赋值 - 它是一个初始值设定项。
What you need is a 'conversion' constructor that takes a
const char*
:The line you're having a problem with:
isn't really an assignment - it's an initializer.
正如其他人指出的那样,“string”具有 const char * 类型,您应该为其重载赋值运算符。
从指针
*this
获取引用就足够了,不需要强制转换任何内容。As others pointed out,
"string"
hasconst char *
type and you should overload assignment operator for it.To get a reference from a pointer
*this
is suffice, no need to cast anything.返回对“this”的引用而不是
它的副本(最好的做法是
对输入参数也这样做
因为你不会不必要地做一个
输入字符串的副本),
const char const* 指针
returns a reference to 'this' and not
a copy of it (it's good practice to
do that for the input parameter too
as you're then not uneccessarily making a
copy of the input string),
const char const* pointer