加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在C中显式调用原始运算符函数

发布时间:2020-12-16 03:27:43 所属栏目:百科 来源:网络整理
导读: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) { re
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参考词汇表明这是不可行的?

解决方法

首先,将内置运算符作为函数调用将不起作用,因为语言规范从未说过存在这样的函数.内置操作符只是操作符.它们背后没有实现功能,因为语言规范从未暗示它们的存在.基于函数的实现仅适用于重载运算符.

其次,在重载解析期间,内置运算符确实由它们虚构的函数类似对应物表示,但禁止“内置运算符”的“显式”函数式调用的措辞存在于13.6 / 1中

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读