簡體   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