Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.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++ 使用动态_转换检测派生类时指针出错_C++_Oop_Inheritance_Polymorphism_Dynamic Cast - Fatal编程技术网

C++ 使用动态_转换检测派生类时指针出错

C++ 使用动态_转换检测派生类时指针出错,c++,oop,inheritance,polymorphism,dynamic-cast,C++,Oop,Inheritance,Polymorphism,Dynamic Cast,我想在我面临的一个问题上得到一些帮助 我用类Shape和Circle(派生自Shape)的polymorph程序进行了继承。所以我有一些这样的代码 main.cpp Shape* shape = new (nothrow) Shape[size](); input_circle(shape); show_circle_area(shape); 还有main.cpp中的一个过程 void show_circle_area(Shape *mshape){ int i; sort(m

我想在我面临的一个问题上得到一些帮助

我用类Shape和Circle(派生自Shape)的polymorph程序进行了继承。所以我有一些这样的代码

main.cpp

Shape* shape = new (nothrow) Shape[size]();
input_circle(shape);
show_circle_area(shape);
还有main.cpp中的一个过程

void show_circle_area(Shape *mshape){
    int i;
    sort(mshape,mshape+totshape,sortByArea);
    cout << "CIRCLE" << endl;
    for (i=0;i<totshape;i++)
        if (dynamic_cast<Circle*> (mshape[i]))
            cout << mshape[i].getWidth() << " " << mshape[i].getArea() << " " << mshape[i].getPerimeter() << endl;
}
void显示圆形区域(Shape*mshape){
int i;
排序(mshape、mshape+totshape、sortByArea);
你的问题在这里:

mshape[totshape]=crl;
本作业仅将
crl
中的“形状部分”复制到
mshape[totshape]
中,因此
mshape[totshape]
仍然是一个形状,而不是一个圆

为了解决您的问题,请使用Shape*指针数组而不是Shape值:

Shape* shape[size]; // we should write this as size is a const
并且,您的
输入功能:

void input_circle(Shape* mshape[]){
    ifstream file;
    int i;
    double r;
    file.open("circle.txt");
    while (file >> r){
        Circle* crl = new Circle(r);
        mshape[totshape]=crl;
        totshape++;
    }
    file.close();
}
请注意,函数原型已更改,请对其他函数执行此操作,并使用
mshape[i]->foo
而不是
mshape[i].foo

现在的演员阵容是:
if(dynamic_cast(mshape[i]){

不要忘记在结束之前释放内存,因为我们正在使用指针:

for (int i = 0; i < totshape; i++) delete mshape[i];

否则,圆、矩形…的析构函数将不会被调用。

您有一个
Shape
数组,而不是
Shape*
数组。其中没有任何内容可以
dynamic\u cast
,也没有
Circle
。(请阅读相关内容。)@molbdnilo我有一些包含圆形的形状,请参阅我的完整主视图。cpp@Alvin不,所有这些派生对象都将被切片。您应该改用
std::vector
。您需要分配圆(等)动态:@TartanLlama使用sliced意味着什么?所以我必须将其更改为vector?无法使其像我想要的那样工作?感谢您的帮助,它解决了大部分问题,我已经更新了完整的main.cpp。我可以问另一个问题吗?当我调用此方法时,是否有可能只打印矩形而不打印正方形(shape);
?您的Square类是否继承矩形?请显示这些类的定义。
void input_circle(Shape* mshape[]){
    ifstream file;
    int i;
    double r;
    file.open("circle.txt");
    while (file >> r){
        Circle* crl = new Circle(r);
        mshape[totshape]=crl;
        totshape++;
    }
    file.close();
}
for (int i = 0; i < totshape; i++) delete mshape[i];
class Shape {
    public:
        virtual ~Shape() {...}
}