2013-12-18 153 views
-1

當我試圖編譯這段代碼編譯錯誤

using namespace std; 
namespace asf{ 
inline int operator|(int); 
} 

asf::operator|(int x){ 
return (x>1)?x*operator|(x-1):1; 
} 

int main(){ 
    cout<<5|; 
} 

我收到以下錯誤

[Error] 'int asf::operator|(int)' must have an argument of class or enumerated type 
[Error] ISO C++ forbids declaration of 'operator|' with no type [-fpermissive] 
[Error] 'int asf::operator|(int)' should have been declared inside 'asf' 
[Error] 'int asf::operator|(int)' must have an argument of class or enumerated type 
In function 'int main()': 
[Error] expected primary-expression before ';' token 

有什麼不對?請幫忙。

+2

你不能在'int'上重載'|'。另外,'|'是一個二元運算符。 – Shahbaz

回答

5

正如錯誤所述,重載操作符必須至少有一個類或枚舉類型的參數。這就是語言的工作原理。

此外,您不能在超載時更改運算符的參數。你試圖定義一個單一的|,這也是非法的。 |必須總是有兩個參數。 operator |的聲明只有在類中聲明時纔會包含一個參數,在這種情況下,左側操作數隱含了類的類型。

+0

假設我改變了符號,即我沒有超載,那麼?我可以使用這個操作員!也許? –

+1

@SoumadeepSaha你不能定義你自己的操作符(至少不是以經典的方式,有一些黑客,但他們不推薦) – Erbureth