修改这段代码使其可以运行:#include <iostream> #include <cmath> using namespace std; class Shape{ public: virtual double GetArea()=0; virtual double GetPerimeter()=0; }; class Circle:public Shape{ double r1; public: Circle(double _r):r1(_r){} double GetArea(){ return 3.14*r1*r1; } double GetPerimeter(){ return 2*3.14*r1; } }; class Outside:public Shape{ double r2; public: Outside(double _r):r2(_r){} double GetArea(){ return 4*r2*r2; } double GetPerimeter(){ return 8*r2; } }; class Inside:public Shape{ double r3; public: Inside(double _r):r3(_r){} double d=sqrt(2*r3*r3); double GetArea(){ return d*d; } double GetPerimeter(){ return 4*d; } }; int main(){ Shape *C=new Circle(2.0); cout<<C->GetArea()<<" "<<C->GetPerimeter<<endl; Shape *O=new Outside(2.0); cout<<O->GetArea()<<" "<<O->GetPerimeter<<endl; Shape *I=new Inside(2.0); cout<<I->GetArea()<<" "<<I->GetPerimeter<<endl; delete C; delete O; delete I; return 0; }
时间: 2023-12-10 20:39:47 浏览: 61
已修改的代码如下:
```
#include <iostream>
#include <cmath>
using namespace std;
class Shape {
public:
virtual double GetArea()=0;
virtual double GetPerimeter()=0;
};
class Circle:public Shape {
double r1;
public:
Circle(double _r):r1(_r){}
double GetArea(){
return 3.14*r1*r1;
}
double GetPerimeter(){
return 2*3.14*r1;
}
};
class Outside:public Shape {
double r2;
public:
Outside(double _r):r2(_r){}
double GetArea(){
return 4*r2*r2;
}
double GetPerimeter(){
return 8*r2;
}
};
class Inside:public Shape {
double r3;
public:
Inside(double _r):r3(_r){}
double GetArea(){
double d=sqrt(2*r3*r3);
return d*d;
}
double GetPerimeter(){
double d=sqrt(2*r3*r3);
return 4*d;
}
};
int main() {
Shape *C=new Circle(2.0);
cout<<C->GetArea()<<" "<<C->GetPerimeter()<<endl;
Shape *O=new Outside(2.0);
cout<<O->GetArea()<<" "<<O->GetPerimeter()<<endl;
Shape *I=new Inside(2.0);
cout<<I->GetArea()<<" "<<I->GetPerimeter()<<endl;
delete C;
delete O;
delete I;
return 0;
}
```
主要问题是 Inside 类中的 `d` 定义在类的外部,需要在 `GetArea()` 和 `GetPerimeter()` 中重新定义。此外,在输出 `C->GetPerimeter()` 时,应该加上括号。
阅读全文