是否不可能手动调用c++操作符?

Is it not possible to call C++ operators manually?

本文关键字:c++ 操作符 调用 不可能 是否      更新时间:2023-10-16

我正在努力更仔细地理解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))仅适用于操作符函数:

13.5重载操作符[over.oper]

4。操作符函数通常不直接调用;相反,他们被调用来计算它们实现的操作符(13.5.1 -13.5.7)。方法显式地调用它们operator-function-id作为函数调用中的函数名语法(22)。(例子:

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

端例子)

操作符函数要求至少一个形参是类类型或枚举类型:

13.5重载操作符[over.oper]

6。操作符函数必须是非静态成员函数或者是一个非成员函数,并且至少有一个参数的类型为是类、对类的引用、枚举还是对枚举。

这意味着仅取int s的运算符函数operator+()不可能存在于13.5/6中。显然,不能在不存在的操作符函数上使用函数调用语法。

对于int, float, double;操作符已经重载/预定义,因此不能做任何特别的操作。,

int z = x + y;

是表达/调用它的唯一方式。

对于的解释目的,实际上这两个语句,

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

操作符重载仅适用于对象和结构体,而不适用于基本类型(如int或float)。如果您有一个对象类,如:

  class A {
    A operator+(const A& rhs) {
      return someComputedValue;
    }
  }

则可以调用myA.operator+(anotherA),这将相当于myA + anotherA

当两个参数都是内置类型时,不能重载二元操作符。但是,对于您自己的对象,您可以这样创建它们。

//Simple struct that behaves like an int.
struct A
{
  int v_;
  explicit A(int i) : v_(i) {}  
  // A member operator so we can write a+b
  A operator+(const A & a ) const { return A( v_ + a.v_); }      
};
// A non-member operator, so we can write 1+a
A operator+(int i, const A & a)
{
   return A(i+a.v_);
}
int main()
{
  A a(1);
  A b(2);
  // Call the member version using its natural syntax    
  A c = a+b;
  //Call the member version using function call syntax
  A d = a.operator+(b);
  // Call the non-member version using the natural syntax
  A e = 1 + b;
  // Call the nonmember version using function call syntax.
  A f = ::operator+(1,b);
}

正如在评论和其他回答中提到的那样,基本类型没有operator+。对于类,operator+(x,y)x.operator+(y)哪个是正确的答案是"这取决于"。特别是,它取决于operator+是如何定义的。如果它被定义为成员函数,则需要使用x.operator+(y)。如果它被定义为一个全局函数,那么你需要使用operator+(x,y)

当编译器遇到语句z=x+y;时,你的编译器足够聪明,可以寻找合适的形式。你不应该期待其中之一。您应该使用x+y

对于本机类型,操作符不是函数。只有重载操作符才是函数。内置操作符是内置的——它们没有"函数",它们通常只是编译成一两个汇编指令,把它们当作函数来调用简直是疯了。

所以operator+(x, y)x.operator+(y)都不正确。我认为x.operator+(y)不太正确,因为非struct类型不能有成员,但我怀疑这有多大帮助。