0
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= 一样。

谢谢。

4

4 回答 4

5

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

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

您遇到问题的行:

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

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

于 2009-12-24T05:05:25.537 回答
3
mystring& operator=(const string &ss) 
{
    cout << "mystring : mystring operator=(string) : " + s <<endl;
    s = ss;

    return *this; // return the reference to LHS object.
} 
于 2009-12-24T04:56:40.327 回答
0

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

mystring& operator=(const char * s);

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

于 2009-12-24T05:01:30.780 回答
0
 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* 指针
于 2009-12-24T09:02:56.430 回答