Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/134.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 通过点到类之间的“动态_cast”转换_C++_Class_Casting_Compiler Errors_Dynamic Cast - Fatal编程技术网

C++ 通过点到类之间的“动态_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<

我尝试通过以下方式通过动态_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