我认为可以通过Derived类的实例(或派生自Derived类的任何类,可以访问Base类的受保护成员,因为它们公开从后者继承)。
但是在尝试在以下列表中执行此操作时出现错误。那我错过了什么?
class Base{
private:
virtual void f(){cout << "f of Base" << endl;}
public:
virtual ~Base(){}
virtual void g(){this->f();}
virtual void h(){cout << "h of Base "; this->f();}
};
class Derived: protected Base{
public:
virtual ~Derived(){}
virtual void f(){cout << "f of Derived" << endl;}
private:
virtual void h(){cout << "h of Derived "; this->f();}
};
int main(){
Base *base = new Base();
cout << "Base" << endl;
base->g(); //f of Base
base->h(); //h of Base f of Base
Derived *derived = new Derived();
cout << "Derived" << endl;
derived->f(); //f of Derived
derived->g(); //this doesn't compile and I get the error "void Base::g() is inaccessible within this context". Why?
derived->h(); //this doesn't compile given that h is private in Derived
delete base;
delete derived;
return EXIT_SUCCESS;
}