use*_*645 1 c++ operator-overloading
只是出于好奇.如果允许使用 - >通过指针调用函数,为什么不通过 - >调用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;
}
Run Code Online (Sandbox Code Playgroud)
错误:
main.cpp:20:9: error: expected unqualified-id before '(' token
ptr->();
Run Code Online (Sandbox Code Playgroud)
我知道ptr-> func()等价于(*ptr).func(),因此可以直接从指针调用重载运算符,而无需解除引用.函数和重载运算符之间的内部差异是什么?