【问题标题】:How does std::string overload the assignment operator?std::string 如何重载赋值运算符?
【发布时间】:2009-12-24 04:49:34
【问题描述】:
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. 如何使正确的 mystring operator= 重载?我认为源代码可以正常工作,但事实证明我仍然无法将 const char[] 分配给 mystring,就好像我没有重载 operator= .

谢谢。

【问题讨论】:

    标签: c++ string operator-overloading stdstring


    【解决方案1】:

    您需要的是一个“转换”构造函数,它采用 const char*:

    mystring( char const* ss) {
      cout << "mystring : mystring(char*) ctor : " << ss <<endl;
      s = ss;
    }
    

    您遇到问题的线路:

    mystring str1 =  "abc"; // why COMPILE ERROR
    

    并不是真正的赋值——它是一个初始化器。

    【讨论】:

    • 如果他想对预先存在的对象执行分配,他需要两者。
    【解决方案2】:
    mystring& operator=(const string &ss) 
    {
        cout << "mystring : mystring operator=(string) : " + s <<endl;
        s = ss;
    
        return *this; // return the reference to LHS object.
    } 
    

    【讨论】:

      【解决方案3】:

      正如其他人指出的那样,"string" 具有 const char * 类型,您应该为其重载赋值运算符。

      mystring& operator=(const char * s);
      

      从指针*this 中获取引用就足够了,不需要转换任何东西。

      【讨论】:

      • Russel 删除了他的答案吗?
      • 嗯,是的,他出于某种原因这样做了。
      • "string" 的类型为 const char[7],而不是 const char *。至于赋值运算符,是的,应该为const char *重载,这是数组将衰减到的类型。
      【解决方案4】:
       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* 指针

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-23
        • 1970-01-01
        • 1970-01-01
        • 2015-07-09
        • 2013-03-30
        • 2013-02-14
        • 2016-08-30
        相关资源
        最近更新 更多