纯虚函数和抽象类
#include <iostream>
using namespace std;
//面向抽象类编程(面向一套预先定义好的接口)
//解耦合
class Figure //抽象类
{
public:
virtual void getArea() = 0;//纯虚函数
protected:
private:
};
class Circle :public Figure
{
public:
Circle(int a, int b)
{
this->a = a;
this->b = b;
}
virtual void getArea()
{
cout << "圆的面积:" << 3.14*a*a << endl;;
}
protected:
private:
int a;
int b;
};
class Tri :public Figure
{
public:
Tri(int a, int b)
{
this->a = a;
this->b = b;
}
virtual void getArea()
{
cout << "三角形的面积为:" << 0.5*a*a<<endl;
}
protected:
private:
int a;
int b;
};
class Sqare :public Figure
{
public:
Sqare(int a, int b)
{
this->a = a;
this->b = b;
}
virtual void getArea()
{
cout << "四边形的面积为:" << a*b<<endl;
}
protected:
private:
int a;
int b;
};
void objplay(Figure *base)
{
base->getArea();//会发生多态
}
void main()
{
Figure *base = NULL;
Circle c1(10, 20);
Tri t1(20, 30);
Sqare s1(50, 60);
objplay(&c1);
objplay(&t1);
objplay(&s1);
system("pause");
return;
}