int a,b,c; //do stuff. For e.g.,cin >> b >> c; c = a + b; //works c = operator+(a,b); //fails to compile,'operator+' not defined.
这另一方面起作用 – @H_404_5@
class Foo { int x; public: Foo(int x):x(x) {} Foo friend operator+(const Foo& f,const Foo& g) { return Foo(f.x + g.x); } }; Foo l(5),m(10); Foo n = operator+(l,m); //compiles ok!
>甚至可以直接调用原始类型的运算符(和其他运算符)(如int)吗?
>如果是,怎么样?
>如果没有,是否有C参考词汇表明这是不可行的?@H_404_5@
解决方法@H_403_14@
首先,将内置运算符作为函数调用将不起作用,因为语言规范从未说过存在这样的函数.内置操作符只是操作符.它们背后没有实现功能,因为语言规范从未暗示它们的存在.基于函数的实现仅适用于重载运算符.
其次,在重载解析期间,内置运算符确实由它们虚构的函数类似对应物表示,但禁止“内置运算符”的“显式”函数式调用的措辞存在于13.6 / 1中@H_404_5@
The candidate operator functions that
represent the built-in operators
defined in clause 5 are specified in
this subclause. These candidate
functions participate in the operator
overload resolution process as
described in 13.3.1.2 and are used for no other purpose.@H_404_5@
其次,在重载解析期间,内置运算符确实由它们虚构的函数类似对应物表示,但禁止“内置运算符”的“显式”函数式调用的措辞存在于13.6 / 1中@H_404_5@
The candidate operator functions that
represent the built-in operators
defined in clause 5 are specified in
this subclause. These candidate
functions participate in the operator
overload resolution process as
described in 13.3.1.2 and are used for no other purpose.@H_404_5@