Win8 VC++2012 を使用しています。
上記のコードは、子クラス B がいかなる状況下でも A::a にアクセスできないことを示しています。A::a のアクセス属性も変更できませんが、A::b と A::c は変更できません。
したがって、A::c は A から B に継承されません。しかし、sizeof(A) と sizeof(B) はそれぞれ 12 と 24 です。これは、A::a DO が 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;
}