如何解决C ++中结构的类型安全转换
我有两个层次的结构层次。我想将顶级父引用作为参数发送到函数中。参数的实际值将是bottomMost子代。该函数应将子代转换为topParent下面的one类型的结构。如果子级属于转换父级,则函数应该成功,否则,则失败。
下面是设计:
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
}
someFunction()的职位是为了验证bottomMost子级是否属于特定父级。但是someFunction()不会为child21抛出。有人可以lmk如何实现吗?
这里是一个适用于两级转换的示例。不知道如何将其扩展为三个级别:How do I cast a parent class as the child class
感谢您的帮助。
解决方法
来自cppreference:
如果强制转换失败并且new-type是指针类型,则它将返回该类型的空指针。如果强制转换失败并且new-type是引用类型,则它将引发与std :: bad_cast类型的处理程序匹配的异常。
您的 new_type
是一个指针,因此不会抛出。您提供的代码也不会编译(缺少函数的返回类型,传递了错误的参数)。
这是您的代码,使用引用而不是指针来引发dynamic_cast
。并且还提供了使用指针的版本,该版本也可以抛出。
#include <exception>
#include <iostream>
struct Parent {
virtual ~Parent() = default;
};
struct Child1 : public Parent {
virtual ~Child1() = default;
};
struct Child2 : public Parent {
virtual ~Child2() = default;
};
struct Child11 : public Child1 {
~Child11() = default;
};
struct Child21 : public Child2 {
~Child21() = default;
};
// void someFunction(Parent* parent) {
// Child1* child1 = dynamic_cast<Child1*>(parent);
// if (!child1) {
// throw std::bad_cast();
// }
// }
void someFunction(Parent& parent) {
Child1& child1 = dynamic_cast<Child1&>(parent);
}
int main() {
Child11 child11;
someFunction(child11); // this should succeeed
Child21 child21;
try {
someFunction(child21); // this should throw
} catch (std::bad_cast) {
std::cout << "Exception caught.\n";
}
}
我认为此练习纯粹是学术性的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。