美文网首页
C++ 虚函数

C++ 虚函数

作者: 菜鸟瞎编 | 来源:发表于2019-06-15 16:48 被阅读0次

C++多态--虚函数virtual及override

如果 不是虚函数,指向子类对象的基类指针只能调用基类的函数,如果是虚函数,就能调用子类的函数。
示例一,非虚函数,指向子类对象的基类指针调用基类函数:

#include <iostream>

using namespace std;


class A{
public:
     void fun(){
        cout<<"A:fun()"<<endl;
    }
};

class B :public A{
public:
    void fun(){
        cout<<"B:fun()"<<endl;
    }
};


int main() {
    cout << "hello https://tool.lu/" << endl;
    
    A * pb = new B();
    pb->fun();
    
    return 0;
}

结果:

hello https://tool.lu/
A:fun()

示例二,虚函数,指向子类对象的基类指针调用子类函数:

#include <iostream>

using namespace std;


class A{
public:
     virtual void fun(){
        cout<<"A:fun()"<<endl;
    }
};

class B :public A{
public:
    void fun(){
        cout<<"B:fun()"<<endl;
    }
};


int main() {
    cout << "hello https://tool.lu/" << endl;
    
    A * pb = new B();
    pb->fun();
    
    return 0;
}

结果:

hello https://tool.lu/
B:fun()

相关文章

网友评论

      本文标题:C++ 虚函数

      本文链接:https://www.haomeiwen.com/subject/xrgbfctx.html