给定一个指针调用括号重载

che*_*erd 9 c++ syntax operator-overloading parentheses

我可以使用以下签名重载括号运算符:

char& operator()(const int r, const int c);
Run Code Online (Sandbox Code Playgroud)

这个用途的目的是:

// myObj is an object of type MyClass
myObj(2,3) = 'X'
char Y = myObj(2,3);
Run Code Online (Sandbox Code Playgroud)

这符合我的预期.但是,在处理指针时使用括号运算符会变得复杂.我想要做:

// pMyObj is a pointer to an object of type MyClass
pMyObj->(2,3) = 'X';
char Y = pMyObj->(2,3);
Run Code Online (Sandbox Code Playgroud)

但是,这种语法会产生错误Error: expected a member name(至少在VisualStudio中).

下面的确有效,但对于我来说,除了参数之外还有更多的括号和更多的括号.

char X = (*pMyObj)(2,3);
Run Code Online (Sandbox Code Playgroud)

有没有办法使用->运算符来调用()重载?

Luc*_*ore 15

是的,但你不会喜欢它:

pMyObj->operator()(2,3);
Run Code Online (Sandbox Code Playgroud)

  • @chessofred嗯,实际上还有另一种方法:不要重载operator()而是使用一个具有可读名称的函数:例如,`pMyObj-> itemAt(2,3)` (2认同)