Meg*_*ron 1 c++ inheritance casting
我有一个我无法修改的struct simple_instr.我从中创建一个派生类型:
struct ComplexInstruction : simple_instr
{
ComplexInstruction(const simple_instr& simple) : simple_instr(simple)
{
}
bool isHead;
bool isTail;
bool isPreHeader;
};
Run Code Online (Sandbox Code Playgroud)
我希望能够判断simple_instr的实例是否实际上是ComplexInstruction.我像这样创建ComplexInstructions:
ComplexInstruction comInstr = *current; // current is a pointer to a simple_instr
ComplexInstruction* cInstr = &comInstr;
Run Code Online (Sandbox Code Playgroud)
我尝试使用
ComplexInstruction* cInstr = static_cast<ComplexInstruction*>(current);
并检查它是否等于null,但问题是转换总是成功,而cInstr永远不会等于null.
这样做的正确方法是什么?
这是一个糟糕的情况:首先,你通常不希望从没有虚拟析构函数的类派生; 做错事太容易了.
"检查对象类型"的内置方法是尝试dynamic_cast使用该类型并查看是否成功.因为你的基类不是多态(它不具有任何虚成员函数),你不能做到这一点.
至少有几个选择.按顺序越来越好:
理想情况下,你应该改变你的设计:使用的,而不是继承组成或找到一些方法来改变基类.
不要忘记对象是这样的事实ComplexInstruction:无论你需要依赖它是什么ComplexInstruction,确保你有一个ComplexInstruction*或者ComplexInstruction&.
跟踪作为simple_instr对象的基础子对象的所有ComplexInstruction对象.在每个ComplexInstruction构造函数中,在全局列表中保存指向其simple_instr基础子对象的指针,并在析构函数中从列表中删除指针.然后,您可以提供一个函数bool IsComplexInstruction(const simple_instr*),检查是否simple_instr是列表(由"表"我的意思是概念上的列表,无论是std::vector或std::set很可能是理想的,这取决于你有多少对象有).