C++ - 多态与虚函数

2016-01-25  本文已影响176人  Mitchell

虚函数

class base{
      virtual int get();
};
int base::get(){}

多态的变现形式一

class CBase{
    public:
        virtual void SomeVirtualFunction(){}
};
class CDerived:public CBase{
    public:
        virtual void SomeVirtualFunction(){}
};
int main() {
    CDerived ODerived;
    CBase * p = & ODerived;
//调用哪个虚函数取决于p 指向哪种类型的对象,编译的时候是不会知道的,直到运行的时候才会知道。
    p-> SomeVirtualFunction();
    return ();
}

多态的表现形式二

class CBase{
    public:
        virtual void SomeVirtualFunction(){}
};
class CDerived:public CBase{
    public:
        virtaul void SomeVirtualFunction(){}
};
int main(){
     CDerived ODerived;
     CBase & r = ODerived;
//调用哪个虚函数取决于 r 引用哪中类型的对象
    r. SomeVirtualFunction();
    return 0;
}

多态的作用

在面向对象的程序设计中使用多态,能够增强程序的可扩充性,即程序需要修改或增加功能的时候,需要改动和增加的代码比较少。

上一篇 下一篇

猜你喜欢

热点阅读