//32dk2j_cpp_纯虚函数与抽象类cc32a_demo-txwtech
//纯虚函数是用来继承用的
//纯虚函数
//抽象类-抽象数据类型
//*任何包含一个或者多个纯虚函数的类都是抽象类
//*不要/不能创建这个类的对象,应该/只能继承它
//*务必覆盖从这个类继承的纯虚函数
//实现纯虚函数-----------可写可以不写
//C++接口
//就是只包含纯虚函数的抽象基类
//32dk2j_cpp_纯虚函数与抽象类cc32a_demo-txwtech
//纯虚函数是用来继承用的
//纯虚函数
//抽象类-抽象数据类型
//*任何包含一个或者多个纯虚函数的类都是抽象类
//*不要/不能创建这个类的对象,应该/只能继承它
//*务必覆盖从这个类继承的纯虚函数
//实现纯虚函数-----------可写可以不写
//C++接口
//就是只包含纯虚函数的抽象基类
#include <iostream>
using namespace std;class Shape//老子--//包含一个或者多个纯虚函数的类就是抽象类
{
public:Shape(){}virtual ~Shape() {}virtual double GetArea()=0;//纯虚函数virtual double GetPerim()=0;//纯虚函数//virtual void Draw() {}virtual void Draw() = 0;//=0就是纯虚函数
};
////纯虚函数可以写,一般不写
//void Shape::Draw() //这个就是实现 这个纯虚函数
//{
// cout << "...";
//}
class Circle :public Shape//儿子
{//没有覆盖纯虚函数,还是抽象类//如下覆盖的操作
public:Circle(int radius) :itsRadius(radius) {}//构造函数//析构函数-//因为GetArea() 与GetPerim()是继承来的,所以还是虚函数//只要类里面有一个虚函数,那么析构函数也需要做成虚的,不然要出错virtual ~Circle() {}//三个纯虚函数重写后,就不是虚的了。double GetArea() {return 3.14*itsRadius*itsRadius;}double GetPerim(){return 2 * 3.14*itsRadius;}void Draw();
private:int itsRadius;
};
void Circle::Draw()
{cout << "circle drawing routine" << endl;Shape::Draw();//调用基类的纯虚函数
}
class Rectangle :public Shape//儿子
{
public:Rectangle(int len,int width):itsWidth(width),itsLength(len) {}virtual ~Rectangle() {}double GetArea() { return itsLength * itsWidth; }double GetPerim() { return 2 * itsWidth + 2 * itsLength; }virtual int GetLength() { return itsLength; }virtual int GetWidth() { return itsWidth; }void Draw();
private:int itsWidth;int itsLength;};
void Rectangle::Draw()
{for (int i = 0; i < itsLength; i++){for (int j = 0; j < itsWidth; j++){cout << "x"; //<< endl;}cout << endl;}Shape::Draw();//调用基类的纯虚函数
}
class Square :public Rectangle //孙子
{
public:Square(int len);Square(int len,int width);virtual ~Square() {};double getPerim() { return 4 * GetLength(); }};
Square::Square(int len) :Rectangle(len, len) {}
Square::Square(int len, int width) : Rectangle(len, width)
{if (GetLength() != GetWidth())cout << "Error,not a square...a rectangle???" << endl;
}int main()
{Circle a(8);a.Draw();Rectangle b(5,10);b.Draw();Square c(8);c.Draw();int choice;bool fQuit = false;Shape *sp=nullptr;//一个指向基类的指针可以指向它的派生类,指向它的子子孙孙//C++的特性//Shape *sp; //vs2017中必须初始化指针while (fQuit == false){cout << "(1)circle (2)Rectangle (3)Square (0)Quit:";cin >> choice;switch (choice){case 1:sp = new Circle(5);//指针必须使用new创建对象break;case 2:sp = new Rectangle(4, 6);break;case 3:sp = new Square(5);break;case 0:fQuit = true;break;/*default:break;*/}if (fQuit == false){sp->Draw();delete sp;cout << endl;}}getchar();return 0;
}