帮我修改以下代码的错误#include<iostream> using namespace std; class Shape{ protected: int r; public: shape(int r); virtual double surfaceArea()=0; virtual double volume()=0; }; Shape::Shape(int r):r(r){ } class Ball:public Shape{ public: Ball(int r); double surfaceArea() override; double volume() override; }; Ball::Ball(int r):Shape(r){ } double Ball::surfaceArea(){ return 4*3.14*r*r; } double Ball::volume(){ return 4.0/3*3.14*r*r*r; } class Cylinder:public Shape{ private: int height; public: Cylinder(int r,int height); double surfaceArea() override; double volume() override; }; Cylinder::Cylinder(int r,int height):Shape(r),height(height){ } double Cylinder::surfaceArea(){ return 2*3.14*r*r+height*2*3.14*r; } double Cylinder::volume(){ return 3.14*r*r*height; } void show(shape *p){ cout <<"表面积"<<p->surfaceArea()<<endl; cout <<"体积"<<p->volume()<<endl; } int main() { Ball ball(1); show (&ball); Cylinder c(1,1); show(&c); return 0; }
时间: 2023-12-14 11:35:59 浏览: 81
以下是修改后的代码:
```c++
#include<iostream>
using namespace std;
class Shape{
protected:
int r;
public:
Shape(int r);
virtual double surfaceArea()=0;
virtual double volume()=0;
};
Shape::Shape(int r):r(r){ }
class Ball:public Shape{
public:
Ball(int r);
double surfaceArea() override;
double volume() override;
};
Ball::Ball(int r):Shape(r){ }
double Ball::surfaceArea(){
return 4*3.14*r*r;
}
double Ball::volume(){
return 4.0/3*3.14*r*r*r;
}
class Cylinder:public Shape{
private:
int height;
public:
Cylinder(int r,int height);
double surfaceArea() override;
double volume() override;
};
Cylinder::Cylinder(int r,int height):Shape(r),height(height){ }
double Cylinder::surfaceArea(){
return 2*3.14*r*r+height*2*3.14*r;
}
double Cylinder::volume(){
return 3.14*r*r*height;
}
void show(Shape *p){
cout <<"表面积:"<<p->surfaceArea()<<endl;
cout <<"体积:"<<p->volume()<<endl;
}
int main() {
Ball ball(1);
show (&ball);
Cylinder c(1,1);
show(&c);
return 0;
}
```
主要修改包括:
1. Shape类的构造函数名应该为Shape,而不是shape;
2. show函数的参数类型应该为Shape*,而不是shape*;
3. Ball和Cylinder类的构造函数定义中,圆的半径应该为r,而不是R;
4. 输出表面积和体积时,应该加上“:”符号。
阅读全文