其他分享
首页 > 其他分享> > c – 派生类私有方法被调用

c – 派生类私有方法被调用

作者:互联网

我有一个指向派生类对象的Base类指针.方法foo()在基类中是公共的,但在派生类中是私有的.基类foo()是虚拟的.因此,当我从Base类指针调用foo()时,Vptr Table具有派生类foo()的地址,但它在Derived类中是私有的……所以如何调用它.

我理解运行时多态性,我也理解Access说明符适用于编译时,虚拟概念在运行时工作.所以应该没有编译器错误.

我的问题是:这是一个循环漏洞,通过它我们可以调用派生类的私有方法吗?或者它的预期表现如此.
对此行为有任何好的解释.

非常感谢提前.

代码:

class A
{
public:
    virtual void foo()
    {
        std::cout << "In A";
    }
};


class B:public A
{
private:
    void foo()
    {
       std::cout << "In B ??? Its Private Method :-( ";
    }
};

int main()
{
    A* ptr = new B();
    ptr->foo();
    return 0;
}

解决方法:

它是私有方法,但由于它是虚拟的 – 它可以被调用.

n3690 11.5 / 1

The access rules (Clause 11) for a virtual function are determined by its declaration and are not affected by
the rules for a function that later overrides it.

为什么这个?以来

n3690 11.5 / 2

Access is checked at the call point using the type of the expression used to denote the object for which the
member function is called (B* in the example above). The access of the member function in the class in
which it was defined (D in the example above) is in general not known.

标签:c,ooad
来源: https://codeday.me/bug/20191007/1864374.html