在 C++ 中显式调用原始运算符函数
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.
另一方面,这有效 -
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++ 参考用语明确表明这是不可行的?
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.
This on the other hand works -
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!
- Is it even possible to invoke operator+ (and other operators) of primitive types (like int) directly?
- If yes, how?
- If not, is there a C++ reference verbiage that makes it clear that this is not doable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,将内置运算符作为函数调用是行不通的,因为语言规范从未说过此类函数存在。内置运算符只是运算符。它们背后没有实现函数,只是因为语言规范从未表明它们的存在。基于函数的实现仅特定于重载运算符。
其次,在重载解析期间,内置运算符确实由其虚构的类函数对应项表示,但禁止“显式”类函数调用内置运算符的措辞出现在 13.6/1 中
Firstly, invoking built-in operators as functions will not work simply because the language specification never says that such functions exist. Built-in operators are just operators. There are no implementing functions behind them simply because the language specification never suggests their existence. Function-based implementations are specific to overloaded operators only.
Secondly, during overload resolution the built-in operators are indeed represented by their imaginary function-like counterparts, but the wording that prohibits "explicit" function-like invocation of built-in operators is present in 13.6/1
来自 http://www.parashift.com/c++-faq-lite/ inside-types.html
我可以定义一个与内置/内在/原始类型一起使用的运算符重载吗?
C++ 标准§13.5.6
From http://www.parashift.com/c++-faq-lite/intrinsic-types.html
Can I define an operator overload that works with built-in / intrinsic / primitive types?
C++ Standard §13.5.6