C++--问题3--多态

C++--问题3--多态


  多态:用同一个东西表示不同的形态

  多态分为:

              静态多态:编译时的多态

              动态多态:运行时的多态

代码1:静多态

class Shape { 
protected: int width, height; 
public: 
    Shape( int a=0, int b=0) { 
       width = a; height = b;
    } 
    int area() { 
    cout << "Parent class area :" <<endl;
    return 0; 
    }
};

当上面的代码被编译和执行时,它会产生下列结果:

Parent class area

Parent class area

       输出的原因是,调用函数 area() 被编译器设置为基类中的版本,这就是所谓的静态多态,或静态链接 ,函数调用在程序执行前就准备好了。有时候这也被称为早绑定,因为 area() 函数在程序编译期间就已经设置好了。

       现在,在 Shape 类中,area() 的声明前放置关键字 virtual,如下所示:

代码2:动多态

class Shape { 
protected: int width, height;
public: 
    Shape( int a=0, int b=0) { 
       width = a; height = b;
    } 
    virtual int area() { 
        cout << "Parent class area :" <<endl;
        return 0; 
    }
};

修改后,当编译和执行前面的实例代码时,它会产生以下结果:

Rectangle class area

Triangle class area

          此时,编译器看的是指针的内容,而不是它的类型。因此,由于 tri 和 rec 类的对象的地址存储在 *shape 中,所以会调用各自的 area() 函数。        

         正如结果,每个子类都有一个函数 area() 的独立实现。这就是多态的一般使用方式。有了多态,您可以有多个不同的类,都带有同一个名称但具有不同实现的函数,函数的参数甚至可以是相同的。

猜你喜欢

转载自blog.csdn.net/qq_41103495/article/details/108500466