几何形体实例

image.png
image.pngimage.png

  1. class CShape {
  2. public:
  3. virtual double Area() = 0; // 纯虚函数
  4. virtual void PrintInfo() = 0;
  5. };
  6. class CRectangle:public CShape {
  7. public:
  8. int w,h;
  9. virtual double Aree();
  10. virtual void PrintInfo();
  11. };
  12. class CCircle:public CShape {
  13. public:
  14. int r;
  15. virtual double Aree();
  16. virtual void PrintInfo();
  17. };
  18. class CTriangle:public CShape {
  19. public:
  20. int a,b,c;
  21. virtual double Aree();
  22. virtual void PrintInfo();
  23. };
  1. double CRectangle::Area() {
  2. return w * h;
  3. }
  4. void CRectangle::PrintInfo() {
  5. cout << "Rectangle:" << Area() << endl;
  6. }
  7. double CCircle::Area() {
  8. return 3.14 * r * r;
  9. }
  10. void CCircle::PrintInfo() {
  11. cout << "Circle:" << Area() << endl;
  12. }
  13. double CTriangle::Area() {
  14. double p = (a+b+c)/2.0;
  15. return sqrt(p * (p-a) * (p-b) * (p-c));
  16. }
  17. void CTriangle::PrintInfo() {
  18. cout << "Triangle:" << Area() << endl;
  19. }
  1. CShape * pShapes[100];
  2. int MyCompare(const void * s1, const void * s2);
  3. int main() {
  4. int i; int n;
  5. CRectangle * pr; CCircle * pc; CTriangle * pt;
  6. cin >> n;
  7. for(i=0; i < n; ++i) {
  8. char c;
  9. cin >> c;
  10. switch(c) {
  11. case 'R':
  12. pr = new CRectangle();
  13. cin >> pr->w >> pr->h;
  14. pShapes[i] = pr;
  15. break;
  16. case 'C':
  17. pc = new CCircle();
  18. cin >> pc->r;
  19. pShapes[i] = pc;
  20. break;
  21. case 'T':
  22. pt = new CTriangle();
  23. cin >> pt->a >> pt->b >> pt->c;
  24. pShapes[i] = pt;
  25. break;
  26. }
  27. }
  28. qsort(pShapes, n, sizeof(CShape*), MyCompare);
  29. for(i=0;i<n;++i)
  30. pShapes[i]->PrintInfo();
  31. return 0;
  32. }
  1. int MyCompare(const void * s1, const void * s2) {
  2. double a1, a2;
  3. CShape** p1; // s1, s2是void *,不可以写“*s1”来取得s1指向的内容
  4. CShape** p2;
  5. p1 = (CShape**)s1; // s1,s2指向pShapes数组中的元素,元素类型是CShape*
  6. p2 = (CShape**)s2;
  7. a1 = (*p1)->Area(); // 多态
  8. a2 = (*p2)->Area();
  9. if(a1 < a2)
  10. return -1;
  11. else if(a2 < a1)
  12. return 1;
  13. else
  14. return 0;
  15. }
  • 如果添加一个新的几何形体,增加的语句只有这个多出来的类
  • 用基类指针数组存放指向各种派生类对象的指针,然后遍历数组,就可以对派生类对象进行各种操作,这是很常用的做法

    另一个例子

    1. class Base {
    2. public:
    3. void fun1() {this->fun2();} // this是基类指针,fun2是虚函数,所以是多态
    4. // 所以如果不加this->,执行效果也一样
    5. virtual void fun2() { cout << "Base::fun2()" << endl;}
    6. };
    7. class Derived:public Base {
    8. public:
    9. virtual void fun2() {cout << "Derived::fun2()" << endl;}
    10. }
    11. main() {
    12. Derived d;
    13. Base * pBase = &d;
    14. pBase->fun1(); // 输出 Derived::fun2()
    15. }
  • 在非构造函数,非析构函数的成员函数中调用虚函数,就是多态

  • 否则不是多态。编译的时候即可确定,调用的是自己类或基类中定义的函数,不会等到运行的时候才决定调用自己的还是派生类的函数

image.png