gpt4 book ai didi

c++ - 不能手动调用 C++ 运算符吗?

转载 作者:IT老高 更新时间:2023-10-28 22:33:02 25 4
gpt4 key购买 nike

我正在尝试更仔细地理解 C++ 中的运算符。

我知道 C++ 中的运算符基本上只是函数。我不明白的是,该功能是什么样的?

举个例子:

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

最后一行如何翻译?是吗:

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

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

当我尝试它们时,编译器错误。是我说错了还是C++中的操作符不能直接调用?

最佳答案

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

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]

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

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.

这意味着在 13.5/6 中不能存在仅采用 int 的运算符函数 operator+()。而且你显然不能对一个不存在的操作符函数使用函数调用语法。

关于c++ - 不能手动调用 C++ 运算符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7225962/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com