繁体   English   中英

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");

所以问题是

  1. 如何创建正确的mystring&opeartor =重载?也就是说,我该如何返回引用而不是指针?(我们可以在C ++中在引用和指针之间转换吗?)

  2. 我以为源代码可以正常工作,但事实证明我仍然无法为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;
 }
  • 我在您的字符串中添加了“&”,以便它返回对“ this”的引用,而不是其副本(这也是对输入参数进行引用的一种很好的做法,因为这样您就不必不必要地复制输入字符串) ,
  • 我在第2行中将“ +”替换为“ <<”
  • 我将您的数组更改为const char const *指针

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM