C++
1.点-圆-圆柱
2.覆盖面向对象程序设计中的封装、继承和多态三大基本特征。
3.基类和派生类分别拥有不少于6个成员函数(函数功能可自行确定),至少包括构造函数、拷贝构造函数和析构函数。
4.在基类或派生类中进行运算符重载的操作,所重载的运算符不限,但个数至少为2个,一个重载为成员函数,一个重载为友元函数。
刚刚学,不太懂。有人可以帮写并给点注释吗?
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- CSDN专家-link 2021-07-18 19:31关注
#include <stdlib.h> #include <iostream> using namespace std; class Point //点类 { private: int px,py; //x和y坐标值 public: Point() {}//默认无参构造函数 ~Point() {}//析构函数 Point(int x,int y) {px = x;py = y;} //带参构造函数 Point(Point &p) {px = p.getX();py = p.getY();} //拷贝构造函数 int getX() {return px;} int getY() {return py;} void setX(int x) {px = x;} void setY(int y) {py = y;} }; class Circle : public Point { private: int radius; public: Circle() {} ~Circle() {} Circle(int x,int y,int r) : Point(x,y){radius = r;} Circle(Circle &c) {radius = c.getR();setX(c.getX());setY(c.getY());} int getR() {return radius;} void setR(int r) {radius = r;} virtual float getArea() {return 3.14159*radius*radius;} //虚函数,计算面积 }; class Cylinder : public Circle { private: int high; public: Cylinder() {} ~Cylinder() {} Cylinder(int x,int y,int r,int h) : Circle(x,y,r){high = h;} Cylinder(Cylinder &c) {high = c.getH();setR(c.getR());setX(c.getX());setY(c.getY());} int getH() {return high;} void setH(int h) {high = h;} float getVolume() {return Circle::getArea()*high;} //计算体积 float getArea() {return 2*3.14159*getR()*high;} //计算面积 void operator = (Cylinder &c) {high = c.getH();setR(c.getR());setX(c.getX());setY(c.getY());} //赋值操作符重载 friend bool operator == (Cylinder &c1,Cylinder &c2);//等于操作符重载 }; bool operator == (Cylinder &c1,Cylinder &c2) { if(c1.getX() == c2.getX() && c1.getY() == c2.getY() && c1.getR() == c2.getR() && c1.getH() == c2.getH()) return true; return false; } int main() { Cylinder c1(10,20,5,20); Cylinder c2(c1); //拷贝构造函数测试 Cylinder c3 = c1; //赋值操作符测试 if(c3 == c2) //等于操作符测试 cout<<"c3与c2相等"<<endl; cout<<"圆柱体积为"<<c3.getVolume()<<endl; //强制调用基类虚函数测试 Circle *p = &c1; cout<<"圆柱面积为"<<p->getArea()<<endl; //虚函数测试 return 0; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥100 关于使用MATLAB中copularnd函数的问题
- ¥20 在虚拟机的pycharm上
- ¥15 jupyterthemes 设置完毕后没有效果
- ¥15 matlab图像高斯低通滤波
- ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
- ¥15 钢筋实图交点识别,机器视觉代码
- ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
- ¥50 400g qsfp 光模块iphy方案
- ¥15 两块ADC0804用proteus仿真时,出现异常
- ¥15 关于风控系统,如何去选择