关于c ++虚函数的困惑

时间:2016-01-22 08:17:29

标签: c++ function virtual member-functions

看看以下两节课。当我在" main"中调用函数时,编译和程序运行时会发生什么?

#include <iostream>
#include <string>
using namespace std;
class A{
public:
    virtual void fun2(){cout<<"A::fun2"<<endl;}
};
class B : public A{
public:
    void fun2(){cout<<"B::fun2"<<endl;}
};
int main() {
    A *a = new B();
    B *b = new B();
    //What's the differences among the followings?
    a->A::fun2();
    b->A::fun2();
    A::fun2();

    return 0;
}

我知道打印的程序是什么,但我想知道为什么。我知道对象中有一个虚函数表,但是当我调用

  

A-&gt;一种:: FUN2()

,它是如何工作的?因为在a或b的v表中,fun2()将打印B :: fun(),程序如何进入函数A :: fun2()?

2 个答案:

答案 0 :(得分:1)

a->A::fun2();

将打印A :: fun2

b->A::fun2();

将打印A :: fun2

A::fun2();

不会被编译

答案 1 :(得分:0)

从您通过显式作用域操作符调用成员函数的那一刻起,例如

instanceptr->Scope::memberfun()

它不再是虚函数调用。该函数不再通过v-table机制调用。

示例中的B类扩展了A类,但这并不意味着成员函数A::fun2()的代码不再存在 - 它就在您的目标文件中,并且编译器只是直接调用该函数