[英]Does protected inheritance allow the derived class access the private members of its base class?
[英]Why can't I access protected members of base class in derived instances using protected/private inheritance?
我認為,派生類的實例(或派生於派生類的任何類,只要它們是從派生類公開繼承的)都可以訪問基類的受保護成員。
但是在以下清單中嘗試執行此操作時出現錯誤。 那我想念什么呢?
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;
}
由於Derived
繼承自Base
protected
LY,所有公共成員Base
都是protected
中Derived
。 這意味着在“ Derived
之外(例如,在main
),這些成員的名稱不可見。
[class.access.base]/1
[...]如果使用
protected
訪問說明符將一個類聲明為另一個類的基類,則可以將基類的公共成員和受保護成員作為派生類的受保護成員進行訪問。 [...]
[class.access]/1.2
班級成員可以是
(1.2)受保護; 也就是說,它的名稱只能由聲明它的類的成員和朋友,該類派生的類及其朋友使用(請參閱[class.protected])。
派生-> g();
可以通過將繼承更改為public來訪問。
派生-> h();
可以通過將派生類內部的訪問說明符從私有更改為公共來進行訪問(由於繼承類指針指向其成員函數,因此仍將繼承保持為受保護狀態)
當您聲明由Derived
繼承的Base
的protected
繼承時,如下所示
class Derived: protected Base
您基本上是在派生類的protected
Base
類protected
成員的所有公共方法。 如果您改為通過以下方式將繼承聲明為公共
class Derived: public Base
您會發現您將能夠很好地訪問derived->g()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.