2013-12-18 185 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