我正在尝试确认我已经在实践中工作的东西背后的理论。完整的设置有点扭曲,因为功能在不同的 dll 之间分割,但我将尝试描述这种情况:
class __declspec( dllexport ) BaseClass
/** This class' definition is available to everything,
* via .h file, .dll and .lib. */
{
protected:
std::string name;
public:
std::string GetName();
/** This is implemented in BaseClass, and just returns this->name. */
}
class DerivedClass: public BaseClass
/** This class is created within the executable, but is not 'visible' to other
* dlls - either through .h files, .lib, or anything else. */
{
public:
DerivedClass();
/** This sets this->name based on its own propertied. */
}
这种向上转换有效,但它需要完全访问 DerivedClass 的定义:
void* pointer;
DerivedClass* derived_pointer = reinterpret_class<DerivedClass*>(pointer);
BaseClass* base_pointer = dynamic_cast<BaseClass*>(derived_pointer);
base_pointer->GetName();
但是,以下内容不起作用:
void* pointer;
BaseClass* base_pointer = reinterpret_class<BaseClass*>(pointer);
base_pointer->GetName();
为了解决这个问题,我实现了一个接口:
class __declspec( dllexport ) IBaseClass
/** Fully virtual 'interface' class, in same file as BaseClass. */
{
public:
virtual std::string GetName() = 0;
}
class __declspec( dllexport ) BaseClass: public IBaseClass
/** This class' definition is available to
* everything, via .h file, .dll and .lib. */
{
protected:
std::string name;
public:
std::string GetName();
/** This is implemented in BaseClass, and just returns this->name. */
}
class DerivedClass: public BaseClass
/** This class is created within the executable, but is not 'visible'
* to other dlls - either through .h files, .lib, or anything else. */
{
public:
DerivedClass();
/** This sets this->name based on its own propertied. */
}
现在下面的代码确实有效:
void* pointer;
IBaseClass* ibase_pointer = reinterpret_class<IBaseClass*>(pointer);
ibase_pointer->GetName();
我有一些模糊的记忆,有人告诉我强制转换为完全虚拟的类是一种特殊情况 - 但我不记得为什么,或者在网上找到任何关于它的信息。
请帮助我 - 为什么我的代码有效?!