2016-02-20 25 views
-2

該第一部分是一個網絡例如可以重載賦值操作符來爲用戶定義的字符串類型分配字符串文字嗎?

分配:

可以分配一個C++字符串,一個C字符串,或C字符串文字到C++字符串。

例子:

string s1 = "original string"; 
string s2 = "new string"; 
char s3[20] = "another string"; 

s1 = s2;//s1 changed to "new string" 
s1 = s3;//s1 changed to "another string" 
s1 = "yet another string"; 
    //s1 changed to "yet another string" 
    //Once again, this works because. 
    //operator overloading. 

這在技術上是低於

class my_string{ 
public: 
. 
. 
my_string& operator=(const my_string&); 
. 
. 
. 
}; 

我的問題,如果這是允許的,然後 怎麼做s1獲得在上面的例子中"yet another string"值的唯一分配 運算符重載?

+0

1.您的[tag:c]標記錯誤,2.您的'string'對象和字符串文字不是「* strings *」,在[tag:C++]的上下文中,您應該小心區分這些之間。 –

+1

你的問題是什麼?你在問如何允許這個任務,或者你是否在說這個任務是允許的,並問爲什麼? – Barmar

+0

您的類是否有任何構造函數從另一個字符串類型轉換爲'my_string'? – Barmar

回答

1

如果我正確理解你的問題,那是因爲它不是唯一的賦值運算符,還有其他重載定義。這些是針對C++ 98的,還有一些針對C++ 11的。

string& operator= (const string& str); 
string& operator= (const char* s); 
string& operator= (char c); 

http://www.cplusplus.com/reference/string/string/operator=/

s1 = "yet another string";使用該列表中的第二個運營商,而s1 = s2;使用第一個。

0

從理論上講,我們必須提供一個重載的賦值運算符是這樣的:

string& operator= (const char* s); 

,但我測試了它。沒有它沒關係。

int main() 
{ 
    mystring s = "assss"; 
    cout << s << endl; 
    s = "aaaaaaaaa"; 
    cout << s << endl; 
    system("pause"); 
    return 0; 
} 

enter image description here

也許編譯器會調用這一個:mystring(const char * st); 然後創建一個臨時對象,將其分配給S1。