假设有如下所示的一个继承关系:

虚函数中的变量作用域问题

对于实例:Derive d; 的虚函数表如下:

虚函数中的变量作用域问题

 

例如:

class Base
{
public:
    virtual void Show()
    {
        cout << a << endl;
    }
    static int a;
};

class Derived : public Base
{
public:
    virtual void Show()
    {
         cout << a << endl;
    }
    static int a;
};

int Base::a = 1;
int Derived::a = 2;

int main(int argc, char *argv[])
{
    Base *p = new Derived;
    p->Show();
    delete p;
    p = NULL;
    return 0;
}

则输出为1,理由是虚函数表中指向Show是Base::Show,因此,很自然里面调用的变量只能是Base作用域的a!

相关文章:

  • 2021-05-20
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-13
  • 2021-12-18
猜你喜欢
  • 2021-11-29
  • 2021-11-21
  • 2021-08-24
  • 2021-04-18
  • 2022-12-23
  • 2021-08-28
  • 2022-12-23
相关资源
相似解决方案