2012-03-13 110 views
0

我一直在做一些工作,需要有一些它們的運算符重載(=,==,+,!=等)我編寫運算符函數,但有時它們是沒有被調用,或者編譯器的行爲就像它不存在一樣。 例如:運算符不解析爲運算符函數C++

class Thing{ 
public: 
    Thing& operator=(const Thing& _other){ 
     // implementation 
    } 
    bool operator==(const Thing& _other){ 
     // implementation 
    } 
    Thing& operator+(const Thing& _other){ 
     // implementation 
    } 
}; 

這是包括類(構造(默認),構造(副本),析構函數,等等)的其他成員函數,但有時該方法被忽略。

void Foo(Thing & thing1, Thing & thing2){ 
    //snip 
    if(thing1 == thing2){ 
     //do some stuff 
    } 
    //snip 
    Thing tempThing(); 
    thing1 = thing2 + &tempThing; 
    //snip 
} 

在視覺工作室我去編譯,它trows沒有操作員需要的東西的左側參數,然後如果我指定thing2->operator+(&tempThing);那麼它的工作原理,這是令人困惑,因爲它應該可以解決該如果存在一個Class operator#(Class)函數,並且參數可以轉換爲合適的類型,那麼所有需要的就是使用該運算符,並且編譯器將用運算符函數代替它,或者至少調用操作員功能。

thing1 = thing2 + thing3; // written line 
thing1.operator=(thing2.operator+(thing3)); 

爲什麼我需要指定操作符函數。編譯器不應該爲我做這件事。

編輯:這是一個關於一般行爲的問題,而不是實際的代碼正確性。即使我編寫語句,因爲他們應該由於某種原因必須指定實際的operator(),而不是隻能使用該符號。 (我曾與直接的例子,以及複製字符的字符要做到這一點,但有時它的工作)

回答

2

這是常見的款式有operator+operator-,等等,你的類或類和operator+=operator-= ...朋友的功能,作爲一個成員函數。這是因爲後者正在修改對象本身,而第一個對象正在處理兩個對象並返回第三個對象。下面是string類的樣本代碼可能看起來像:

class string { 
public: 
     string& operator+=(const string& other) 
     { 
       this->append(other); 
       return *this; 
     } 
private: 
     void append(const string& other) 
     { 
       // concatenate two strings here 
     } 
}; 

string operator+(const string& first, const string& second) 
{ 
     string result(first); 
     result += second; 
     return result; 
} 

對於您的情況下改變線

Thing tempThing(); 
thing1 = thing2 + &tempThing; 

Thing tempThing; 
thing1 = thing2 + tempThing; 

也應該工作。

1

要添加功能

Thing tempThing(); 
thing1 = thing2 + &tempThing; 

Thing tempThing();的指針聲明返回事物的功能,Thing tempThing;創建事情

也:

operator==, operator+ 

小號應該可能是const

4
Thing tempThing(); 

這不是你可能認爲的原因。谷歌的「最令人頭疼的解析」。

thing1 = thing2 + &tempThing; 

由於您operator+需要引用(不是指針),你不想把地址。一旦你解決了前面的定義,它應該編譯好,如thing1 = thing2 + tempThing;

但是,一般來說,您希望避免使用成員函數來重載大多數操作符。問題在於,這樣做可以將右操作數轉換爲正確的類型,而不是左操作數。通過使用全局超載,您可以獲得對稱性 - 可以轉換操作數。