定义类方法的错误总结

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);
}

即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值