gpt4 book ai didi

c++ - 使用后期绑定(bind)从非私有(private)上下文调用私有(private)方法

转载 作者:行者123 更新时间:2023-11-30 02:51:49 26 4
gpt4 key购买 nike

我对下面这段代码 (g++ 4.4.7) 产生的输出感到惊讶。

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

class B : public A {
private:
// Automatically virtual, because of base class
void f() {std::cout << "B::f()" << std::endl;}
};

int main(int argc, const char *argv[])
{
A *pB = new B();
pB->f();
return 0;
}

输出是

B::f()

我知道因为后期绑定(bind)编译器不能在这里发出错误,但为什么我们可以从非私有(private)上下文中调用私有(private)方法?

理由是什么?

最佳答案

n3376 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.

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. The access of the member function in the class inwhich it was defined (D in the example above) is in general not known.

关于c++ - 使用后期绑定(bind)从非私有(private)上下文调用私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19448777/

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