2016-03-14 26 views
0

當試圖將operator!=作爲朋友函數內聯時,出現編譯器錯誤undefined reference to嵌入式運算符!=未定義的引用

下面是一個例子:

// color.hpp 
class Color 
{ 
    friend bool operator==(const Color& lhs, const Color& rhs); 
    inline friend bool operator!=(const Color& lhs, const Color& rhs); 
}; 

// color.cpp 
bool operator==(const Color& lhs, const Color& rhs) 
{ 
} 

inline bool operator!=(const Color& lhs, const Color& rhs) 
{ 
} 

我無法實現在頭文件中的運營商,因爲這會產生多個定義錯誤。

我在編譯--std=c++11,g ++ 5.2。

+3

如果您在聲明朋友函數時刪除'inline',是否可以執行此項工作? – vu1p3n0x

+0

不,這沒有幫助 – user3728501

回答

0

從類定義中刪除inline

類定義後,在頭文件中,添加以下:

inline bool 
operator!=(const Color& lhs, const Color& rhs) 
{ 
    return !(lhs == rhs); 
} 

刪除在源文件中的定義。

+0

這似乎編譯,除了我得到'運算符=='多個定義錯誤,這是不是使用'inline'聲明的 – user3728501

+0

其中一個是在其他當然實現 – user3728501

+0

移動'運算符=='回到'.cpp'文件,它工作,爲什麼?! – user3728501