CC20020419 2022-04-19 16:25 采纳率: 85%
浏览 28
已结题

面积计算,为什么这段程序输出是空白(语言-c++)


#include<bits/stdc++.h>
using namespace std;
class Shape{
    public:
    virtual    double Area();
    protected:
        double area;
};
class Circle:public Shape{
    public:
        Circle(int a);
        double Area();
    protected:
        int radius;
        double PI=3.14159;
       
        
};
class Rectangle:public Shape{
    public:
        Rectangle(int width1,int height1);
        double Area();
    protected:
        int width;
        int height;
};
double Shape::Area(){return area;}
Circle::Circle(int a){
    radius=a;
}
double Circle::Area(){
     area=PI*radius*radius;
}
Rectangle::Rectangle(int width1,int height1){
    width=width1;
    height=height1;
}
double Rectangle::Area(){
     area=width*height;
}
int main(){
    
    Shape *p[4];
    p[0]=new Circle(1);
    p[1]=new Circle(2);
    p[2]=new Rectangle(1,2);
    p[3]=new Rectangle(3,4);
    for(int i=0;i++;i<4){
        cout<<p[i]->Area()<<endl;
    }
    delete p;
    
}

样例输出
3.14
12.56
2
12

  • 写回答

2条回答 默认 最新

  • bostonAlen 2022-04-19 22:21
    关注

    new 和 delete得成对使用
    另外p是一个数组,如果你使用Shape *p = new Shape[4];的形式创建了对象
    那么你必须使用delete [] p; 释放空间

    int main() {
    
        Shape *p[4];
        p[0] = new Circle(1);
        p[1] = new Circle(2);
        p[2] = new Rectangle(1, 2);
        p[3] = new Rectangle(3, 4);
        for (int i = 0; i < 4; i++ ) {
            cout << p[i]->Area() << endl;
        }
        delete p[0];
        delete p[1];
        delete p[2];
        delete p[3];
        return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 4月30日
  • 已采纳回答 4月22日
  • 创建了问题 4月19日

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?