是不是可以手动调用C ++操作符? [英] Is it not possible to call C++ operators manually?

查看:142
本文介绍了是不是可以手动调用C ++操作符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更仔细地了解C ++中的运算符。



我知道C ++中的运算符基本上只是函数。我没有得到的是,这个功能是什么样子?



以例如:

  int x = 1; 
int y = 2;
int z = x + y;

最后一行如何翻译?是:



1。 int z = operator +(x,y);




$ b b p 2。 int z = x.operator +(y);



当我尝试这两个时,编译器错误。

解决方案

使用C ++ standardese,函数调用语法( operator +(x,y) x.operator +(y))仅适用于:


13.5重载的操作符[over.oper]



4。操作员函数通常不直接调用;而是调用
来评估它们实现的运算符(13.5.1 -
13.5.7)。然而,可以使用
operator-function-id 作为函数调用
语法(5.2.2)中的函数名称来显式调用它们。 [示例:

  complex z = a.operator + // complex z = a + b; 
void * p = operator new(sizeof(int)* n);

-end example ]


< blockquote>

和操作符函数至少需要一个类类型或枚举类型的参数:


13.5重载操作符[over.oper]



6。 -static成员函数
或者是一个非成员函数,并且至少有一个参数类型
是类,对类的引用,枚举或对
的引用枚举。


这意味着操作符函数 operator +() code> int s不能存在每13.5 / 6。你显然不能对不能存在的操作符函数使用函数调用语法。


I'm trying to understand operators in C++ more carefully.

I know that operators in C++ are basically just functions. What I don't get is, what does the function look like?

Take for example:

int x = 1;
int y = 2;
int z = x + y;

How does the last line translate? Is it:

1. int z = operator+(x,y);

or

2. int z = x.operator+(y);?

When I tried both of them, the compiler errors. Am I calling them wrong or are operators in C++ not allowed to be called directly?

解决方案

Using C++ standardese, the function call syntax (operator+(x, y) or x.operator+(y)) works only for operator functions:

13.5 Overloaded operators [over.oper]

4. Operator functions are usually not called directly; instead they are invoked to evaluate the operators they implement (13.5.1 - 13.5.7). They can be explicitly called, however, using the operator-function-id as the name of the function in the function call syntax (5.2.2). [Example:

    complex z = a.operator+(b); // complex z = a+b;
    void* p = operator new(sizeof(int)*n);

—end example]

And operator functions require at least one parameter that is a class type or an enumeration type:

13.5 Overloaded operators [over.oper]

6. An operator function shall either be a non-static member function or be a non-member function and have at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration.

That implies that an operator function operator+() that only takes ints cannot exist per 13.5/6. And you obviously can't use the function call syntax on an operator function that can't exist.

这篇关于是不是可以手动调用C ++操作符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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