【发布时间】:2013-10-23 22:13:07
【问题描述】:
IClass(我的界面):
#ifndef _ICLASS_H
#define _ICLASS_H
#include <sstream>
namespace Test
{
class __declspec(dllexport) IClass
{
public:
virtual ~IClass() {}
virtual bool Init(const std::string &path) = 0;
};
}
#endif
类.h
#ifndef _CLASS_H
#define _CLASS_H
#include "IClass.h"
#include <memory>
#include <sstream>
#include <stdio.h>
namespace Test
{
class Class: public IClass
{
public:
Class();
~Class();
bool Init(const std::string &path);
};
}
#endif
类.cpp
#include "Class.h"
namespace Test
{
Class::Class()
{
}
bool Class::Init(const std::string &path)
{
try
{
// do stuff
return true;
}
catch(std::exception &exp)
{
return false;
}
}
}
main(在 exe、dll 中隐式链接)
#include "IClass.h"
using namespace Test;
int main(int argc, char* argv[])
{
std::shared_ptr<IClass> test = std::make_shared<Class>(); // error: unreferenced Class
test->Init(std::string("C:\\Temp"));
}
目前 Class 没有被声明
-> 如果我将Class.h 包含在主目录中,则会发生以下错误:LNK2019: unresolved external symbol: add class __declspec(dllexport) Class : public IClass 解决此链接器问题,但可以这样做吗?
-> 我也不能这样做:std::shared_ptr<IClass> test = std::make_shared<IClass>();
(因为不允许创建抽象类的对象)
我该如何解决这个问题,这是最佳做法吗?
【问题讨论】:
-
如果您导出(和导入)类,并包含相关头文件,程序将编译并运行。由于您没有说明您的目标或限制条件,因此无法说这是否是一种好的做法。
-
@DavidHeffernan:查看我的帖子的编辑
-
我仍然不知道你的目标或你的限制。
-
@leon22 我们必须知道您是否想向其用户隐藏“类”的实现细节。我是,请看我的回答:使用工厂函数。如果不这样做,导出 Class 就可以了。