cc32a_demo-32dk2j_cpp_纯虚函数与抽象类-txwtech

时间:2023-03-09 05:01:42
cc32a_demo-32dk2j_cpp_纯虚函数与抽象类-txwtech

//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()=;//纯虚函数
virtual double GetPerim()=;//纯虚函数
//virtual void Draw() {}
virtual void Draw() = ;//=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 * 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 * itsWidth + * itsLength; }
virtual int GetLength() { return itsLength; }
virtual int GetWidth() { return itsWidth; }
void Draw();
private:
int itsWidth;
int itsLength; };
void Rectangle::Draw()
{
for (int i = ; i < itsLength; i++)
{
for (int j = ; 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 * 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();
a.Draw();
Rectangle b(,);
b.Draw();
Square c();
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 :
sp = new Circle();//指针必须使用new创建对象
break;
case :
sp = new Rectangle(, );
break;
case :
sp = new Square();
break;
case :
fQuit = true;
break; /*default:
break;*/
}
if (fQuit == false)
{
sp->Draw();
delete sp;
cout << endl;
} } getchar();
return ;
}