[英]Why does it not work to overload “operator <<” on 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");
所以問題是
如何創建正確的mystring&opeartor =重載?也就是說,我該如何返回引用而不是指針?(我們可以在C ++中在引用和指針之間轉換嗎?)
我以為源代碼可以正常工作,但事實證明我仍然無法為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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.