Jae*_*ege 1 c++ access-control
我的问题是为什么我不能通过指向基类的指针在派生类中调用受保护的虚拟成员函数,除非将派生类声明为基类的朋友?
例如:
#include <iostream>
class A {
friend class C; // (1)
protected:
virtual void foo() const = 0;
};
class B : public A {
void foo() const override { std::cout << "B::foo" << std::endl; }
};
class C : public A {
friend void bar(const C &);
public:
C(A *aa) : a(aa) { }
private:
void foo() const override {
a->foo(); // (2) Compile Error if we comment out (1)
//this->foo(); // (3) Compile OK, but this is not virtual call, and will cause infinite recursion
std::cout << "C::foo" << std::endl;
}
A *a;
};
void bar(const C &c) {
c.foo();
}
int main() {
B b;
C c(&b);
bar(c);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是
B::foo
C::foo
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,我想foo()通过a类的成员调用虚函数C(this在编译时不是静态绑定的),但是如果我不C作为A朋友,则调用是非法的.
我认为C是继承的A,所以它可以访问protected成员A,但为什么它实际上不会发生?