只是出于好奇。如果允许通过指针使用 -> 调用函数,为什么不通过 -> 调用 operator() 呢?
#include <iostream>
using namespace std;
struct point {
int x;
int y;
void show() {cout<< x <<" : "<< y <<endl;}
void operator()() {cout<< x <<" : "<< y <<endl;}
};
int main()
{
point p;
p.x=1; p.y=2;
p();
point* ptr = &p;
ptr->show();
(*ptr)(); // ok
ptr->(); // error
return 0;
}
错误:
main.cpp:20:9: error: expected unqualified-id before '(' token
ptr->();
我知道 ptr->func() 等同于 (*ptr).func(),因此可以直接从指针调用重载运算符,而无需取消引用。函数和重载运算符之间的内部区别是什么?
最佳答案
代替ptr->()
,编写ptr->operator()()
。
关于c++为什么不能使用->使用指针调用重载(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20462313/