【发布时间】:2018-10-21 05:30:13
【问题描述】:
我认为基类的受保护成员可以被派生类(或派生自派生类的任何类,因为它们公开继承自后者)的实例访问。
但在以下列表中尝试执行此操作时出现错误。那我错过了什么?
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;
}
【问题讨论】:
-
为什么在这里使用虚拟继承?
-
语法错误,并不意味着在继承子句中包含 virtual。我会解决的
-
derived->h() ,你不能访问类外的私有成员;在派生类中,成员函数被声明为私有。
标签: c++ inheritance protected