C++ c+中结构的类型安全铸造+;
我有两个层次的结构。我想将顶级父ref作为param发送到函数中。param的实际值将是最底层的子级。该函数应将子对象强制转换为topParent下面的OneType结构。如果子函数属于强制转换父函数,则函数应成功,否则失败 设计如下:C++ c+中结构的类型安全铸造+;,c++,pointers,inheritance,struct,C++,Pointers,Inheritance,Struct,我有两个层次的结构。我想将顶级父ref作为param发送到函数中。param的实际值将是最底层的子级。该函数应将子对象强制转换为topParent下面的OneType结构。如果子函数属于强制转换父函数,则函数应成功,否则失败 设计如下: struct Parent { ~Parent() = default; } struct Child1 : public Parent { ~Child1() = default; } struct Child2 : public Parent {
struct Parent {
~Parent() = default;
}
struct Child1 : public Parent {
~Child1() = default;
}
struct Child2 : public Parent {
~Child2() = default;
}
struct Child11 : public Child1 {
~Child11() = default;
}
struct Child21 : public Child2 {
~Child21() = default;
}
someFunction (Parent* parent) {
Child1 * child1 = dynamic_cast<Child1 *>(parent);
}
main() {
Child11 child11;
someFunction(child11); // this should succeeed
Child21 child21;
someFunction(child21); // this should throw
}
结构父级{
~Parent()=默认值;
}
结构Child1:公共父级{
~Child1()=默认值;
}
结构Child2:公共父级{
~Child2()=默认值;
}
结构Child11:公共Child1{
~Child11()=默认值;
}
结构Child21:公共Child2{
~Child21()=默认值;
}
someFunction(父*父){
Child1*Child1=动态_转换(父级);
}
main(){
儿童11儿童11;
someFunction(child11);//这应该成功
儿童21儿童21;
someFunction(child21);//这应该抛出
}
someFunction()的任务是验证最底层的子级是否属于特定的父级。但是someFunction()不会为child21抛出。有人知道如何做到这一点吗
下面是一个适用于两级铸造的示例。不知道如何将其扩展到三个级别:
感谢您的帮助。来自:
如果强制转换失败,并且new-type是指针类型,则返回该类型的空指针。如果强制转换失败,并且new-type是引用类型,它将抛出一个与std::bad_cast类型的处理程序匹配的异常
您的new_type
是指针,因此不会抛出。所提供的代码也不会编译(函数上缺少返回类型,传递了错误的参数)
这是您的代码,使用引用而不是指针来获取要抛出的dynamic\u cast
。同时还提供了一个使用指针的版本,该版本也可以抛出
#包括
#包括
结构父级{
virtual~Parent()=默认值;
};
结构Child1:公共父级{
virtual~Child1()=默认值;
};
结构Child2:公共父级{
virtual~Child2()=默认值;
};
结构Child11:公共Child1{
~Child11()=默认值;
};
结构Child21:公共Child2{
~Child21()=默认值;
};
//void someFunction(父级*父级){
//Child1*Child1=动态_转换(父级);
//如果(!child1){
//抛出std::bad_cast();
// }
// }
void函数(父函数和父函数){
Child1&Child1=动态_转换(父级);
}
int main(){
儿童11儿童11;
someFunction(child11);//这应该成功
儿童21儿童21;
试一试{
someFunction(child21);//这应该抛出
}捕捉(标准::错误的投射){
std::cout只是在表中没有使用多态性?dynamic_cast
不会抛出。在尝试动态强制转换后,您的函数只会得到nullptr
。如果您想抛出它,请执行If(parent!=nullptr&&child1==nullptr)抛出…
您的代码现在甚至无法编译。您正在传递对象,而函数需要指针。请更正键入错误。