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

标签 c++ inheritance class-visibility

我对下面这段代码 (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 by the 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 the member function is called. 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++ - 使用后期绑定(bind)从非私有(private)上下文调用私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19448777/

相关文章:

c++ - 重载函数不编译的简单 SFINAE 示例

c++ - 从子类c++调用基类方法

swift - 从其父类(super class)函数访问子类类型

java - 为什么不能通过反射访问公共(public)构造函数

c++ - QT 5.4,无法从代码访问资源

c++ - C++中的函数和选择问题

c++ - 未定义对模板常量和函数的引用

c++ - 如何使用委托(delegate)来抽象子类中调用基类成员的方式?

c# - 使用内部类型(C#)声明公共(public)类方法时出现不一致的可访问性错误?

rust - Hack Rust 可见性和隐私