是否不可能手动调用c++操作符?
Is it not possible to call C++ operators manually?
我正在努力更仔细地理解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
类型不能有成员,但我怀疑这有多大帮助。
- 为什么map有操作符[],set没有
- 我可以将C 17 Capture lambda ConstexPR转换操作符的结果用作函数指针模板非类型参数吗?
- c++新操作符通过libstdc++占用大量内存(67MB)
- 复制/移动操作符是否可以安全地用于实现复制/移动分配操作符
- 提升::精神::因果报应使用有条件的替代操作符(|)
- 促进几何体操作符
- 如果操作符delete没有实现,为什么不编译它
- 在使用放置新操作符时,我真的需要担心对齐问题吗
- 我怎样才能让getline操作符工作
- 在重载的全局new操作符中使用静态对象会导致核心转储运行时错误
- 提升ipc new和delete操作符
- 在c++中使用new操作符动态分配数组
- 操作符的大小在C++
- 如何将向量中的对象传递给操作符
- 一个更容易的拷贝分配操作符实现
- 如何重写复杂的c++代码行(嵌套的三元操作符)
- boost::make_shared没有调用(放置)操作符new
- 新操作符(以及malloc)无法分配~450MB的内存
- 类、异常和操作符
- 当delete操作符释放内存时,我为什么需要析构函数