我使用Win8 VC++ 2012。C++子類不能從父類繼承私有成員?
上面的代碼是顯示在任何情況下的子類B都可以訪問A :: a。我也不能改變A :: a的訪問屬性,但是A :: b和A :: c。
所以A :: c未從A繼承到B.但的sizeof(A)和sizeof(B)分別爲12和24,這意味着A ::一個DO中B.
佔據存儲器- B如何將A :: a存儲在內存中,卻永遠無法訪問它?
- 本書C++ Primer說,我們可以恢復基類成員的訪問屬性,但不能改變它。在這裏,我的代碼顯示,我可以在B中將A :: b的訪問屬性從protected更改爲public。爲什麼?
下面的代碼:
#include <iostream>
using namespace std;
class A
{
private:
int a;
protected:
int b;
public:
int c;
A(int a, int b, int c): a(a), b(b), c(c)
{
cout << "A: ";
cout << a << " ";
cout << b << " ";
cout << c << endl;
}
};
class B: protected A
{
private:
int d;
protected:
int e;
//using A::a; COMPILE ERROR
public:
int f;
//A::a; COMPILE ERROR
using A::c; //RESTORE A::c public access
A::b; // change A::b from protected to public
B(int d, int e, int f): A(d, e, f), d(d), e(e), f(f)
{
cout << "B\n";
//cout << a << endl; COMPILE ERROR
cout << b << " ";
cout << c << " ";
cout << d << " ";
cout << e << " ";
cout << f << endl;
}
};
int main()
{
A a(1,2,3);
B b(4,5,6);
cout << "sizeof(A)=" << sizeof(A) << endl; //OUTPUT 12
cout << "sizeof(B)=" << sizeof(B) << endl; //OUTPUT 24
return 0;
}
不要相信'sizeof'能像你期望的那樣工作。 –
另外,你期望什麼? 'private'是'private'。 –