在C ++中显式调用原始操作符函数 [英] Calling primitive operator-functions explicitly in C++

查看:118
本文介绍了在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! 




  • 甚至可以调用操作符+

  • 如果是,如何?

  • 如果没有,是否有一个C ++引用语句,不可行?

  • 推荐答案

    首先,调用内置运算符作为函数不会简单地因为语言规范从来没有说过这样的功能存在。内置运算符只是运算符。它们之后没有实现函数,因为语言规范从来没有表明它们的存在。

    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.

    其次,在重载解析过程中,内建运算符的确由它们的虚函数表示类似的对象,但禁止显式函数式调用内置运算符的措辞存在于13.6 / 1

    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


    候选运算符函数
    表示在第5节中定义的内置运算符

    本子句中指定。这些候选
    函数参与运算符
    重载解决过程,如在13.3.1.2 中描述的
    ,并且被用于
    以用于没有其他目的

    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.

    这篇关于在C ++中显式调用原始操作符函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆