基类指针shape
Cir Tri Rec getC countC 都是派生类 有利用了shape 为了统一接口
注意 shape中的getC 函数前加上virtual
//不同形状图形求周长
#include <stdio.h>
#include<iostream>
using namespace std;
class shape{
public:
virtual double getC(void){
}
};
class Cir:public shape{
public:
Cir(double ri):r (ri){
}
double getC(void)
{
return 2*3.14*r;
}
private:
int r;
};
class Tri:public shape{
public:
Tri(double a,double b,double c):e1(a),e2(b),e3(c){
}
double getC(void)
{
return e1+e2+e3;
}
private:
double e1;
double e2;
double e3;
};
class Rec: public shape{
public:
Rec(double e)
{
this->e=e;
}
double getC(void)
{
return 4*e;
}
private:
double e;
};
double countC(shape *arr[],int n)
{
double sum=0;
for(int i=0;i<n;i++)
{
sum+=arr[i]->getC();
}
return sum;
}
int main()
{
Cir c(1);
Rec r(3);
Cir ci(2);
Tri t(3,3,3);
shape *arr[]={&c,&r,&ci,&t};
cout<<"total C:"<<countC(arr,4)<<endl;
}