定义类方法的错误总结

发布于:2024-10-09 ⋅ 阅读:(116) ⋅ 点赞:(0)
struct Renderer
{
	vector<function<void(vector<string>)>> fileDropListeners;

	// 定义一个方法,它是将一个函数作为输入,callback是形参
	void print(function<void(float)> callback_func);
	void onFileDrop(function<void(vector<string>)> callback) {
		fileDropListeners.push_back(callback);
	}
};

void print(function<void(float)> callback_func) {
	float a;
	std::cin >> a;
	callback_func(a);
}

出现错误:

Build started at 22:10...
1>------ Build started: Project: Project1, Configuration: Debug x64 ------
1>Source.cpp
1>Source.obj : error LNK2019: unresolved external symbol "public: void __cdecl Renderer::print(class std::function<void __cdecl(float)>)" (?print@Renderer@@QEAAXV?$function@$$A6AXM@Z@std@@@Z) referenced in function main
1>D:\work\VSsource\repos\cpplearn\Project1\x64\Debug\Project1.exe : fatal error LNK1120: 1 unresolved externals
1>Done building project "Project1.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
========== Build completed at 22:10 and took 00.793 seconds ==========

想要实现在结构体中仅声明方法,在结构体外进行定义,但是遇到连接错误。原因是下面定义的print并没有正确地定义给结构体中的print方法。而在main()函数中却使用了他。从而出现连接报错。正确修改应该是 : 在结构体外(外命名空间中)定义方法时一定要表明类对象:修改如下:

struct Renderer
{
	vector<function<void(vector<string>)>> fileDropListeners;

	// 定义一个方法,它是将一个函数作为输入,callback是形参
	void print(function<void(float)> callback_func);
	void onFileDrop(function<void(vector<string>)> callback) {
		fileDropListeners.push_back(callback);
	}
};

void Renderer::print(function<void(float)> callback_func) {
	float a;
	std::cin >> a;
	callback_func(a);
}

void lambda(float a) {
	printf("lambda hello %f!", a);
}

即可


网站公告

今日签到

点亮在社区的每一天
去签到