C++类内如何正确调用重载的operator()运算符?
问题原因与解决方案
错误根因
this是指向当前实例的指针,本身不支持函数调用语法,直接写this(*p++)相当于把指针变量当成函数调用,自然会触发expression cannot be used as a function编译错误。
正确调用方式
有两种常用的正确写法:
- 写法1:先对
this解引用拿到实例对象,再调用重载的operator()
(*this)(*p++);
- 写法2:在类成员作用域内直接显式调用运算符成员函数
operator()(*p++);
修改后完整可运行代码
#include <iostream> struct S { void operator()(char c){ std::cout << c << std::endl; }; void operator()(const char * p) { while( *p != '\0' ) { (*this)( *p++ ); // 也可替换为 operator()(*p++); } } } s ; int main() { s( "blqhblqh" ); }
内容的提问来源于stack exchange,提问作者Vorac
相关产品推荐
相关产品推荐

