单例DLL中未定义纯虚函数

时间:2016-03-04 20:31:00

标签: c++ visual-c++ dll interface singleton

我正在尝试构建一个DLL,它将作为Singleton管理我项目的各种配置选项。

我按照提出的方法here in the chosen answer进行了操作,如下所示:

IBuildConfiguration.h

#if defined(BUILD_CONFIGURATION_LIBRARY_EXPORT)
#   define BUILD_CONFIGURATION_API   __declspec(dllexport)
#else
#   define BUILD_CONFIGURATION_API   __declspec(dllimport)
#endif  // BUILD_CONFIGURATION_LIBRARY_EXPORT

class IBuildConfiguration
{
    public:
        virtual int foo(void) = 0; 
};

BUILD_CONFIGURATION_API IBuildConfiguration& Instance(void);

BuildConfiguration.h

class BuildConfiguration : public IBuildConfiguration
{
    public:

        BuildConfiguration();
        ~BuildConfiguration();


        virtual int foo(void);
};

修改:忘记包含Instance()的实施

BuildConfiguration.cpp

int BuildConfiguration::foo(void)
{
    return 1; //just a silly example
}

IBuildConfiguration& Instance(void)
{
    static BuildConfiguration instance;
    return instance;
}

现在,在Visual C ++ 6中,我在我的项目中添加了对这个新DLL的依赖,我在源代码中包含了 IBuildConfiguration 标题:

SystemCtrl.cpp

#include "../../BuildConfiguration/IBuildConfiguration.h"

IBuildConfiguration buildConfig = Instance();

我的DLL已成功构建,但使用它的项目却没有。

不幸的是,这会导致以下错误:

int __thiscall IBuildConfiguration::foo(void)' : pure virtual function was not defined

将DLL和LIB文件复制到项目中似乎无法解决问题。

2 个答案:

答案 0 :(得分:2)

确保您的Instance方法看起来像这样

 IBuildConfiguration& Instance()
 {
    // Creates instance of derived class all is good.
    static BuildConfiguration inst;
    return inst;
 }

而不是:

 IBuildConfiguration& Instance()
 {
    // Tries to create instance of base class.. Not possible as it
    // has pure virtual functions.
    static IBuildConfiguration inst;
    return inst;
 }

Dark Falcon是对的,您需要将Instance()方法的返回值存储在对基类的引用中,否则它将尝试通过调用基类复制构造函数来创建基类的新实例同样的问题: )。

答案 1 :(得分:2)

如果IBuildConfiguration没有纯虚函数,那么这仍然无法正常运行:

IBuildConfiguration buildConfig = Instance();

这基本上表示"从IBuildConfiguration"的返回值复制构造Instance()的实例。派生的类信息将丢失。这是切片。您需要将变量作为参考:

IBuildConfiguration& buildConfig = Instance();