一、要求

先建立一个Point(点)类,包含数据成员x,y(坐标点)。以它为基类,派生出一个Circle(圆)类,增加数据成员r(半径)再以Circle类为直接基类,派生出一个Cylinder(圆柱体)类,再增加数据成员h(高)

要求:

  1. 重载运算符“<<”,使之能输出一个点对象
  2. 在程序中使用虚函数和抽象类。类的层次结构的顶层是抽象基类Shape(形状)。Point(点)、Circle(圆)、Cylinder(圆柱体)都是Shape类的直接派生类和间接派生类

二、分析

由项目要求分析可知,Shape做基类,且void show()做纯虚构函数,之后Point类、Circle类、Cylinder类通过指针分别调用自己的show()函数

C++实验13

三、代码

💻提示:所有实验源码已在github整理

#include<iostream>
using namespace std;

//形状
class Shape
{
public:
virtual void show() = 0;
};

//点类
class Point:public Shape
{
public:
Point(){};
Point(double x, double y)
{
this->x = x;
this->y = y;
}
void setP(double x,double y)
{
this->x = x;
this->y = y;
}
void show()
{
cout << "这是一个点" << endl;
}
friend ostream &operator <<(ostream &out, Point &p0);
private:
double x, y;

};

ostream &operator <<(ostream &out, Point &p0)
{
out <<"("<< p0.x<<","<<p0.y<<")";
return out;
}

//圆类
class Circle:public Point
{
public:
Circle() {};
Circle(double r,double x,double y)
{
this->r = r;
setP(x, y);
}
void setR(double r)
{
this->r = r;
}
void show()
{
cout << "这是一个圆" << endl;
}
private:
double r;
};

//圆柱类
class Cylinder:public Circle
{
public:
Cylinder(double x,double y,double r, double h)
{
setP(x, y);
setR(r);
this->h = h;
}
void show()
{
cout << "这是一个圆柱体" << endl;
}
private:
double h;
};


int main()
{
Point p2(0, 0);
p2.show();
cout << "测试运算符重载 p=" << p2<< endl;

Circle c1(2, 2, 2);
c1.show();

Shape * c = new Circle(3,3,3);//圆
c->show();
delete c;

Shape * cy = new Cylinder(4, 4, 4, 4);//圆柱体
cy->show();
delete cy;

system("pause");
return 0;
}

四、 结果

C++实验14