#include<iostream> using namespace std; class Circle { protected: float radius; public: Circle(float radius = 10) :radius(radius) {} float calcArea() { float area; area = 3.14 * radius * radius; return area; } }; class Cylinder :public Circle { private: float hight; public: Cylinder(float radius = 10, float hight = 1) :radius(radius), hight(hight) {} float calcArea() { float area; area = 2 * Circle::calcArea() + 2 * 3.14 * radius * hight; cout << "圆柱的表面积是" << area << endl; return area; } };纠错这段代码
时间: 2024-03-23 11:38:12 浏览: 104
这段代码存在以下问题:
1. 在Cylinder类的构造函数中,radius和hight都被定义了默认参数,但是在初始化列表中只能有一个默认参数,因此需要修改为只有hight有默认参数。
2. 在Cylinder类的构造函数中,应该调用Circle类的构造函数进行初始化,而不是直接使用radius变量进行初始化。
3. 在Cylinder类的calcArea函数中,应该先调用父类Circle的calcArea函数来计算圆的面积,再计算圆柱的表面积。同时,函数名应该为calcSurfaceArea,而不是calcArea,因为它计算的是表面积而不是面积。
修改后的代码如下:
```
#include<iostream>
using namespace std;
class Circle {
protected:
float radius;
public:
Circle(float radius = 10) :radius(radius) {}
float calcArea() {
float area;
area = 3.14 * radius * radius;
return area;
}
};
class Cylinder :public Circle {
private:
float hight;
public:
Cylinder(float radius = 10, float hight = 1) :Circle(radius), hight(hight) {}
float calcSurfaceArea() {
float area;
area = 2 * Circle::calcArea() + 2 * 3.14 * radius * hight;
cout << "圆柱的表面积是" << area << endl;
return area;
}
};
```
阅读全文