gpt4 book ai didi

c++ - 派生类私有(private)方法被调用

转载 作者:太空宇宙 更新时间:2023-11-03 10:29:44 25 4
gpt4 key购买 nike

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

我理解运行时多态性,我也理解访问说明符在编译时起作用,虚拟概念在运行时起作用。所以应该没有编译器错误。

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

非常感谢。

代码:

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;
}

最佳答案

它是私有(private)方法,但由于它是虚拟的 - 它可以被调用。

n3690 11.5/1

The access rules (Clause 11) for a virtual function are determined by its declaration and are not affected bythe 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 themember function is called (B* in the example above). The access of the member function in the class inwhich it was defined (D in the example above) is in general not known.

关于c++ - 派生类私有(private)方法被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20468027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com