按以下提示信息,由基类的设计和测试开始,逐渐地完成各个类的设计,并且完成要求的功能。 ①设计一个Point(点)类,包含数据成员x、y(坐标点)。 ②以Point为基类,派生出一个Circle(圆)类,增加数据成员r(半径)。 ③以Circle类为直接基类,派生出一个Cylinder(圆柱体)类,再增加数据成员h(高)。 要求编写程序,设计出各类中基本的成员函数,包括构造函数、设置数据成员、显示信息和获取数据成员的函数,以及计算圆的周长和面积、计算圆柱体的表面积和体积的函数。
时间: 2023-06-19 09:06:01 浏览: 73
下面是基类Point的设计和测试代码:
```c++
#include<iostream>
using namespace std;
class Point{
protected:
double x, y;
public:
Point(double _x, double _y):x(_x), y(_y){}
void setX(double _x){
x = _x;
}
void setY(double _y){
y = _y;
}
double getX(){
return x;
}
double getY(){
return y;
}
void display(){
cout<<"("<<x<<", "<<y<<")"<<endl;
}
};
int main(){
Point p(1, 2);
p.display();
p.setX(3);
p.setY(4);
p.display();
return 0;
}
```
接下来是派生类Circle的设计:
```c++
#include<iostream>
#include<cmath>
using namespace std;
class Circle: public Point{
protected:
double r;
public:
Circle(double _x, double _y, double _r):Point(_x, _y), r(_r){}
void setR(double _r){
r = _r;
}
double getR(){
return r;
}
void display(){
cout<<"center: ";
Point::display();
cout<<"r: "<<r<<endl;
}
double getArea(){
return M_PI*pow(r, 2);
}
double getCircumference(){
return 2*M_PI*r;
}
};
int main(){
Circle c(1, 2, 3);
c.display();
cout<<"Area: "<<c.getArea()<<endl;
cout<<"Circumference: "<<c.getCircumference()<<endl;
c.setR(4);
c.display();
cout<<"Area: "<<c.getArea()<<endl;
cout<<"Circumference: "<<c.getCircumference()<<endl;
return 0;
}
```
最后是派生类Cylinder的设计:
```c++
#include<iostream>
#include<cmath>
using namespace std;
class Cylinder: public Circle{
protected:
double h;
public:
Cylinder(double _x, double _y, double _r, double _h):Circle(_x, _y, _r), h(_h){}
void setH(double _h){
h = _h;
}
double getH(){
return h;
}
void display(){
cout<<"center: ";
Point::display();
cout<<"r: "<<getR()<<endl;
cout<<"h: "<<h<<endl;
}
double getVolume(){
return Circle::getArea()*h;
}
double getSurfaceArea(){
return 2*Circle::getArea()+Circle::getCircumference()*h;
}
};
int main(){
Cylinder c(1, 2, 3, 4);
c.display();
cout<<"Volume: "<<c.getVolume()<<endl;
cout<<"Surface Area: "<<c.getSurfaceArea()<<endl;
c.setR(4);
c.setH(5);
c.display();
cout<<"Volume: "<<c.getVolume()<<endl;
cout<<"Surface Area: "<<c.getSurfaceArea()<<endl;
return 0;
}
```
以上代码实现了要求的功能。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)