几何形体实例
class CShape {
public:
virtual double Area() = 0; // 纯虚函数
virtual void PrintInfo() = 0;
};
class CRectangle:public CShape {
public:
int w,h;
virtual double Aree();
virtual void PrintInfo();
};
class CCircle:public CShape {
public:
int r;
virtual double Aree();
virtual void PrintInfo();
};
class CTriangle:public CShape {
public:
int a,b,c;
virtual double Aree();
virtual void PrintInfo();
};
double CRectangle::Area() {
return w * h;
}
void CRectangle::PrintInfo() {
cout << "Rectangle:" << Area() << endl;
}
double CCircle::Area() {
return 3.14 * r * r;
}
void CCircle::PrintInfo() {
cout << "Circle:" << Area() << endl;
}
double CTriangle::Area() {
double p = (a+b+c)/2.0;
return sqrt(p * (p-a) * (p-b) * (p-c));
}
void CTriangle::PrintInfo() {
cout << "Triangle:" << Area() << endl;
}
CShape * pShapes[100];
int MyCompare(const void * s1, const void * s2);
int main() {
int i; int n;
CRectangle * pr; CCircle * pc; CTriangle * pt;
cin >> n;
for(i=0; i < n; ++i) {
char c;
cin >> c;
switch(c) {
case 'R':
pr = new CRectangle();
cin >> pr->w >> pr->h;
pShapes[i] = pr;
break;
case 'C':
pc = new CCircle();
cin >> pc->r;
pShapes[i] = pc;
break;
case 'T':
pt = new CTriangle();
cin >> pt->a >> pt->b >> pt->c;
pShapes[i] = pt;
break;
}
}
qsort(pShapes, n, sizeof(CShape*), MyCompare);
for(i=0;i<n;++i)
pShapes[i]->PrintInfo();
return 0;
}
int MyCompare(const void * s1, const void * s2) {
double a1, a2;
CShape** p1; // s1, s2是void *,不可以写“*s1”来取得s1指向的内容
CShape** p2;
p1 = (CShape**)s1; // s1,s2指向pShapes数组中的元素,元素类型是CShape*
p2 = (CShape**)s2;
a1 = (*p1)->Area(); // 多态
a2 = (*p2)->Area();
if(a1 < a2)
return -1;
else if(a2 < a1)
return 1;
else
return 0;
}
- 如果添加一个新的几何形体,增加的语句只有这个多出来的类
用基类指针数组存放指向各种派生类对象的指针,然后遍历数组,就可以对派生类对象进行各种操作,这是很常用的做法
另一个例子
class Base {
public:
void fun1() {this->fun2();} // this是基类指针,fun2是虚函数,所以是多态
// 所以如果不加this->,执行效果也一样
virtual void fun2() { cout << "Base::fun2()" << endl;}
};
class Derived:public Base {
public:
virtual void fun2() {cout << "Derived::fun2()" << endl;}
}
main() {
Derived d;
Base * pBase = &d;
pBase->fun1(); // 输出 Derived::fun2()
}
在非构造函数,非析构函数的成员函数中调用虚函数,就是多态
- 否则不是多态。编译的时候即可确定,调用的是自己类或基类中定义的函数,不会等到运行的时候才决定调用自己的还是派生类的函数