优化这段代码:#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:33 浏览: 58
以下是优化后的代码:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
class Shape{
public:
virtual double GetArea() const = 0;
virtual double GetPerimeter() const = 0;
};
class Circle : public Shape{
private:
double r;
public:
Circle(double _r) : r(_r){}
double GetArea() const override {
return 3.14 * r * r;
}
double GetPerimeter() const override {
return 2 * 3.14 * r;
}
};
class Outside : public Shape{
private:
double r;
public:
Outside(double _r) : r(_r){}
double GetArea() const override {
return 4 * r * r;
}
double GetPerimeter() const override {
return 8 * r;
}
};
class Inside : public Shape{
private:
double r;
public:
Inside(double _r) : r(_r){}
double GetArea() const override {
double d = sqrt(2) * r;
return d * d;
}
double GetPerimeter() const override {
return 4 * sqrt(2) * r;
}
};
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;
}
```
优化内容:
1. 将 Shape 类中的纯虚函数的返回类型改为 const,以避免意外修改数据。
2. 将 Circle、Outside、Inside 类中的成员变量名更改为更有意义的名字,方便代码阅读。
3. 将 Inside 类中的计算对角线长度的语句放入 GetArea 函数内,避免在类定义中进行计算。
4. 将 Inside 类中的计算周长的语句放入 GetPerimeter 函数内,避免在类定义中进行计算。
阅读全文