Zac*_*ery 1 c++ inheritance private
我正在使用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中的内存.
这是代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
孩子继承父母的私人成员,但他们无法访问它们.要访问它们protected
class A
{
protected: // <<------------ make `a` as protected in parent
int a;
Run Code Online (Sandbox Code Playgroud)