[英]c++ access-specifier understanding
我在線程中遇到以下響應:
可以從派生類訪問受保護的成員。 私人的不能。
class Base {
private:
int MyPrivateInt;
protected:
int MyProtectedInt;
public:
int MyPublicInt;
};
class Derived : Base
{
public:
int foo1() { return MyPrivateInt;} // Won't compile!
int foo2() { return MyProtectedInt;} // OK
int foo3() { return MyPublicInt;} // OK
};
class Unrelated
{
private:
Base B;
public:
int foo1() { return B.MyPrivateInt;} // Won't compile!
int foo2() { return B.MyProtectedInt;} // Won't compile
int foo3() { return B.MyPublicInt;} // OK
};
...
1) 我的問題是 :我已閱讀:“類派生列表命名一個或多個基類,其形式為:
類派生類:訪問說明符基類
其中access-specifier是public,protected或private之一,而base-class是先前定義的類的名稱。 如果未使用訪問說明符,則默認情況下為私有。 和“私有繼承:從私有基類派生時,基類的公共成員和受保護成員將成為派生類的私有成員。
”
所以...在我們的示例中,類Derived:Base與類Derived:private Base等效,因為尚未定義訪問說明符,但代碼按作者所說的工作,所以我錯過了什么?-我認為該Base類適用於class Derived訪問說明符是私有的,因此Base的public和受保護的Base成員對於Derived類應該是私有的,因此無法訪問...謝謝!
這是類似的想法。 與其適用於您可以訪問該類的哪些成員,不如適用於您可以訪問哪些基類。
class A
{
public:
void f();
};
class B : public A
{
public:
void g()
{
f(); // OK
A *a = this; // OK
}
};
class B2 : public B
{
public:
void h()
{
f(); //OK
A *a = this; // OK
};
};
B b;
A& ba = b;
class C : protected A
{
public:
void g()
{
f(); // OK, can access protected base
A *a = this; // OK, can access protected base
}
};
class C2 : public C
{
public:
void h()
{
f(); // OK, can access protected base
A *a = this; // OK, can access protected base
};
};
C c;
c.f(); // Not OK, allthough A::f() is public, the inheritance is protected.
A& ca = c; // Not OK, inheritence is protected.
class D : private A
{
public:
void g()
{
f(); // OK because A is a base of D
A *a = this;
}
};
class D2 : public D
{
public:
void h()
{
f(); //Not OK, A is inherited with private in D
A *a = this; //Not OK
};
};
D d;
d.f(); // Not OK, allthough A::f() is public, the inheritance is private.
D& da = d; // Not OK, inheritence is private.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.