[英]operator not resolving to operator function 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
}
在Visual Studio中,我要進行編譯,結果是沒有運算符采用Thing的左側參數,然后如果我指定thing2->operator+(&tempThing);
那么它起作用了,這是令人困惑的,因為它應該僅依靠語言解析來解析該操作符功能
如果存在Class operator#(Class)
函數,並且可以將參數轉換為適當的類型,則只需使用運算符,然后編譯器將其替換為operator函數,或者至少調用操作員功能。
thing1 = thing2 + thing3; // written line
thing1.operator=(thing2.operator+(thing3));
為什么我必須指定運算符功能。 編譯器不應該為我這樣做。
編輯:這是關於一般行為的問題,而不是代碼的實際正確性。 即使當我出於某些原因編寫語句時,也必須指定實際的operator()而不是僅僅使用符號。 (我不得不使用直接的示例以及逐個字符地復制字符,但這有時確實可行)
Thing tempThing();
這可能不是您想的那樣。 谷歌的“最煩人的解析”。
thing1 = thing2 + &tempThing;
由於您的operator+
引用(而不是指針),因此您不想使用該地址。 修改完前面的定義后,它應該可以編譯為thing1 = thing2 + tempThing;
。
但是,一般而言,您要避免使用成員函數來使大多數運算符重載。 問題在於這樣做允許將右操作數轉換為正確的類型,但不能轉換為左操作數。 通過使用全局重載,您可以獲得對稱性-可以轉換任何一個操作數。
這是常見的款式有operator+
, operator-
等等,你的類或類和朋友的功能operator+=
, operator-=
......,作為一個成員函數。 這是因為后面的對象正在修改對象本身,而第一個對象正在處理兩個對象並返回第三個對象。 這是字符串類的示例代碼,可能類似於:
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;
應該也可以。
您正在添加函數的指針
Thing tempThing();
thing1 = thing2 + &tempThing;
Thing tempThing();
聲明一個返回Thing, Thing tempThing;
創造事物
也:
operator==, operator+
應該是const
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.