我对下面这段代码 (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
11.5.2The 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.
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/