纯虚函数做接口的案例:#include
using namespace std;
class Area
{
public:
virtual void calculate() = 0;
};
class Circle:public Area
{
public:
Circle(int a, int b)
{
this->a = a;
this->b = b;
}
virtual void calculate()
{
cout << “圆的面积是” << 3.14 * a * a << endl;
}
private:
int a;
int b;
};
class Tri :public Area
{
public:
Tri(int a, int b)
{
this->a = a;
this->b = b;
}
virtual void calculate()
{
cout << “三角形的面积是” << a*b/2<< endl;
}
private:
int a;
int b;
};
class Squ :public Area
{
public:
Squ(int a, int b)
{
this->a = a;
this->b = b;
}
virtual void calculate()
{
cout << “长方形的面积是” << a*b << endl;
}
private:
int a;
int b;
};
//搭建多态的舞台
void objplay(Area *base)
{
base->calculate();
}
void main()
{
Circle c1(1, 2);
Tri t1(1, 2);
Squ s1(1, 2);
objplay(&c1);
objplay(&t1);
objplay(&s1);
system("pause");
}