我有一个基类和一个派生类,每个类都有一个.h文件和一个.cpp文件。
在以下代码中,我将基类对象动态转换为派生类:
头文件:
class Base
{
public:
Base();
virtual ~Base();
};
class Derived : public Base
{
public:
Derived(){};
void foo();
};
class Another
{
public:
Another(){};
void bar(Base* pointerToBaseObject);
};
cpp文件:
Base::Base()
{
//do something....
}
Base::~Base()
{
//do something....
}
void Derived::foo()
{
Another a;
a.bar(this);
}
void Another::bar(Base* pointerToBaseObject)
{
dynamic_cast<Derived*>(pointerToBaseObject)
}
出于某种奇怪的原因,强制类型转换失败(返回NULL)。但是,如果我将Derived类的构造函数的实现从.h文件移动到.cpp文件中,强制类型转换就会成功。
这可能是什么原因呢?
编译器是Linux-SUSE上的gcc 3.1。顺便说一下,在Visual Studio中,相同的代码运行良好,只有在这个平台上才会出现这种情况。