C++ 通过点到类之间的“动态_cast”转换
我尝试通过以下方式通过动态_cast进行转换:C++ 通过点到类之间的“动态_cast”转换,c++,class,casting,compiler-errors,dynamic-cast,C++,Class,Casting,Compiler Errors,Dynamic Cast,我尝试通过以下方式通过动态_cast进行转换: #include <iostream> class Shape { //.... }; class Square: Shape { //.... }; class Circle: Shape { //.... }; int main() { Circle cr; Shape* sh = &cr; // ERROR1 Square* psq = dynamic_cast<
#include <iostream>
class Shape {
//....
};
class Square: Shape {
//....
};
class Circle: Shape {
//....
};
int main() {
Circle cr;
Shape* sh = &cr; // ERROR1
Square* psq = dynamic_cast<Square*>(sh); //ERROR2
return 0;
}
我收到错误消息:
错误1:“形状”是“圆”的不可访问的基
错误2:无法将“class Shape*”类型的“sh”动态\u强制转换为“class Square*”类型源类型不是多态的
有人能解释我为什么会出现这些错误吗?第一个错误是,您必须公开继承Shape,才能在派生对象构造中调用Shape的构造函数 第二个错误是因为类形状必须是多态的,这意味着至少有一个虚拟方法:
class Shape {
public:
virtual ~Shape(){}
//....
};
class Square: public Shape {
//....
};
class Circle: public Shape {
};
Circle cr;
Shape* sh = &cr; // ERROR1
Square* psq = dynamic_cast<Square*>(sh);
即使基类形状不是多态的,上面的行也可以正常工作。您可能从类形状私下继承了副本。你应该把它公之于众:class Square:public Shape…@Raindrop7但我还是得到了错误2它与你没有展示给我们的代码有关。因为你把它当作多态类使用。问题是您使用非多态类作为多态类,这是一个矛盾。您能解释一下为什么在这种情况下psq=NULL吗?如果dynamic_cast在强制转换中失败,它将返回nullptr;当要大小写的指针没有要转换到的对象地址时,它会失败。您的代码甚至无法编译!按照我在解决方案中的建议,先编辑它,然后再编辑。
Circle* cr = new Circle;
Shape* shp = dynamic_cast<Shape*>(cr); // upcasting