C++重载operator[]返回函数指针时编译错误的解决建议
解决C++ operator[]重载的函数指针返回类型编译错误
错误原因
你直接将函数指针类型作为operator[]的返回类型,这种写法不符合C++语法规则。编译器会把void (*)后的)误认为是返回类型的结束,后续的operator[]会被当成非法标识符,从而抛出expected unqualified-id before ‘)’ token错误。
解决方案
有三种合法写法可以解决该问题:
方案1:用using定义函数指针类型(C++11及以上推荐)
先在类作用域内或外部定义函数指针的类型别名:
using CommandHandler = void(*)(const dpp::slashcommand_t& event);
再重载operator[]:
CommandHandler operator[](const std::string& index);
方案2:用typedef定义函数指针类型
这是C++11之前的传统写法,兼容性更广:
typedef void(*CommandHandler)(const dpp::slashcommand_t& event);
再重载operator[]:
CommandHandler operator[](const std::string& index);
方案3:使用后置返回类型(C++11及以上)
借助C++11的后置返回类型语法,让返回类型的写法更直观:
auto operator[](const std::string& index) -> void(*)(const dpp::slashcommand_t& event);
内容的提问来源于stack exchange,提问作者AdriaNn01
相关产品推荐
相关产品推荐

