C++
1.点-圆-圆柱
2.覆盖面向对象程序设计中的封装、继承和多态三大基本特征。
3.基类和派生类分别拥有不少于6个成员函数(函数功能可自行确定),至少包括构造函数、拷贝构造函数和析构函数。
4.在基类或派生类中进行运算符重载的操作,所重载的运算符不限,但个数至少为2个,一个重载为成员函数,一个重载为友元函数。
#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;
}