当dynamic_cast
我应用于指向多重继承对象实例的指针时,运算符返回零 (0)。我不明白为什么。
层次结构:
class Field_Interface
{
public:
virtual const std::string get_field_name(void) const = 0; // Just to make the class abstract.
};
class Record_ID_Interface
{
public:
virtual bool has_valid_id(void) const = 0;
};
class Record_ID_As_Field
: public Field_Interface,
public Record_ID_Interface
{
// This class behaves as a Field and a Record_ID.
// ...
}
// A demonstration function
void Print_Field_Name(const Field_Interface * p_field)
{
if (p_field)
{
cout << p_field->get_field_name() << endl;
}
return;
}
// A main function for demonstration
int main(void)
{
Record_ID_As_Field * p_record_id = 0;
p_record_id = new Record_ID_As_Field;
if (p_record_id)
{
// (1) This is the trouble line
Print_Field_Name(dynamic_cast<Field_Interface *>(p_record_id));
}
return 0;
}
我希望将Record_ID_As_Field
其视为一个Field_Interface
,但也适合Record_ID_Interface
需要的地方。
为什么dynamic_cast
在上面的(1)中返回 0,我该如何解决这个问题?
我在 Windows XP 上使用 Visual Studion 2008。
注意:为简单起见,我在此示例中使用基本指针。实际代码使用boost::shared_ptr
.