C++类内初始化存储自定义结构体的vector报构造函数匹配错误
问题根因
报错本质是静态成员table初始化时传入的参数不符合FunctionToUpdate的构造要求,具体是两个问题:
- 类外初始化静态成员时,直接写
&testFunctionA/&testFunctionB属于非法访问:这两个是Error类的成员函数,类外全局作用域无法直接通过非限定名查找,必须加类名前缀&Error::testFunctionA才能找到对应函数。 - 即使补全类名前缀,两个函数是类的非静态成员函数,隐式携带
this指针作为第一个参数,实际函数签名为void (Error::*)(int, Params),和FunctionToUpdate中定义的std::function<void(int, Params)>类型不匹配,无法直接构造std::function对象。
你把所有代码写到单个.cpp文件时问题消失,一般是书写时无意间将函数定义为静态、或是把table初始化放在了类作用域内部,刚好绕过了上述两个限制。
从你给出的函数实现看,testFunctionA和testFunctionB全程没有访问类的非静态成员,本身就应该定义为静态成员函数,这是改造成本最低的修复方式。
修复步骤
- 在头文件的类定义里,给
testFunctionA、testFunctionB加上static修饰,去掉隐式this参数,匹配std::function的签名要求。 - 在.cpp文件的
table初始化部分,给成员函数指针补全类名限定,让编译器可以正确找到函数地址。
修正后完整代码
ErrorHandling.h
#include <vector> #include <functional> #include <iostream> struct Params { std::vector<int> Integers; std::vector<std::string> Strings; }; struct FunctionToUpdate { int Version; std::function<void(int, Params)> Function; Params Parameters; }; class Error { public: Error(); static void testFunctionA(int a, Params p); static void testFunctionB(int a, Params p); protected: const static std::vector<FunctionToUpdate> table; };
main.cpp
#include "ErrorHandling.h" Error::Error() { for (auto functionToUpdate : table) { functionToUpdate.Function(functionToUpdate.Version, functionToUpdate.Parameters); std::cout << "############################################" << std::endl; } std::cout << "Done!" << std::endl; } void Error::testFunctionA(int a, Params parameter) { std::cout << a << std::endl; for (auto& integer : parameter.Integers) { std::cout << integer << std::endl; } // 修正原代码笔误:遍历字符串容器时变量名误写为integer for (auto& str : parameter.Strings) { std::cout << str << std::endl; } } void Error::testFunctionB(int a, Params parameter) { std::cout << a << std::endl; std::cout << parameter.Integers.at(0) << std::endl; } const std::vector<FunctionToUpdate> Error::table { // 补全类名限定 { 100, &Error::testFunctionA, { {177}}}, { 1948, &Error::testFunctionB, { {314}}}, }; int main() { Error error; }
如果你后续需要让这两个函数访问类的非静态成员,就不能用静态函数方案,需要把
FunctionToUpdate里的可调用类型改成成员函数指针,调用时传入当前对象实例即可。
内容的提问来源于stack exchange,提问作者Deto24
相关产品推荐
相关产品推荐

