今日,在工作中遇到了一种以前从没见过的virtual关键字的用法,起初百思不得其解,而后搜索了一下资料进行阅读后算是得出一个说得通的解释。
问题如下:C++ Dll导出类导出函数很常见,当间接方式导出类时,类非静态成员必须加virtual关键字。否则使用该dll的工程会出现链接错误。
test_class.h
#pragma once
class TestClassA
{
public:
static TestClassA* GetInstance();
virtual void funA();
};
////////////////////////////////////////
test_class.cpp
#include "stdafx.h"
#include "test_class.h"
TestClassA* TestClassA::GetInstance()
{
static TestClassA obj;
return &obj;
}
void TestClassA::funA()
{
}
////////////////////////////////////////
interface.h
#include "test_class.h"
#ifdef TEST_EXPORTS
#ifndef TEST_API
#define TEST_API __declspec(dllexport)
#endif
#else
#ifndef TEST_API
#define TEST_API __declspec(dllimport)
#endif
#endif
TEST_API TestClassA* GetClassA();
////////////////////////////////////////
#include "interface.h"
TestClassA* GetClassA()
{
return TestClassA::GetInstance();
}
///////////////////////////////////////
调用的工程
#include "../NakiLib/interface.h"
int _tmain(int argc, _TCHAR* argv[])
{
GetClassA()->funA();
return 0;
}
对此,我能给出的解释是:简单地说,通过virtual关键字,使调用的工程在编译时,因为virtual的特性,无需知道其实现,如果不加这个关键字,就需要funA的具体实现,但是因为没有导出,所以会链接错误。换句话说,这种用法更像是使了点小手段,如果使用C语言来编写,应该无法实现这种间接导出。
参考此贴:
http://bbs.youkuaiyun.com/topics/20163418
q.为什么所有成员函数均为虚函数。
a:如果不是虚函数,其实再连接的时候成员函数是会连接代码到.exe里面去的,这样就根本call不到dll里面的函数,也就没有实现我们的原意。
而虚函数是通过函数指针调用的,exports类是再dll里面构造,所以可以保证虚函数是call到dll里面,而且.exe只需要dll的头文件即可编译连接通过。
真是充分利用了virtual这个关键字的特性啊
了解更多lib,dll,编译的知识:
http://www.cnblogs.com/cainiaozhanchi/archive/2010/08/03/1791615.html
http://www.cnblogs.com/cainiaozhanchi/archive/2010/08/03/1791614.html