C++中派生类列表的访问说明符
理解派生类列表的访问说明符时,应当抛开成员说明符。
派生类列表中:
(1)用public修饰的类,相当于敞开大门的房间,所有派生类和派生类的用户都拥有访问的权利。
(2)用private修饰的类,相当于带锁的房间,除了直接继承的派生类外,其余派生类和所有派生类的对象均没有钥匙(即不可访问)。
(3)用protected修饰的类,相当于带锁的房间,所有的派生类拥有开锁的钥匙,而所有派生类的对象均没有钥匙(即不可访问)。
参考范例
class A
{
public:
A() = default;
A(int i, int j, int k) :a1(i), a2(j), a3(k) {}
int a1;
private:
int a2;
protected:
int a3;
};
class B
{
public:
B() = default;
B(int i, int j, int k) :b1(i), b2(j), b3(k) {}
int b1;
private:
int b2;
protected:
int b3;
};
class C
{
public:
C() = default;
C(int i, int j, int k) :c1(i), c2(j), c3(k) {}
int c1;
private:
int c2;
protected:
int c3;
};
class D :public A, private B, protected C
{
public:
D() = default;
D(int i, int j, int k) :A(i++, j++, k++), B(i++, j++, k++), C(i, j, k) {}
void f()
{
std::cout << a1 << a2 << a3
<< b1 << b2 << b3
<< c1 << c2 << c3
<< std::endl;
}
int d1;
private:
int d2;
protected:
int d3;
};
class E :public D
{
public:
E() = default;
E(int i, int j, int k) :D(i, j, k) {}
void f()
{
std::cout << a1 << a2 << a3
<< b1 << b2 << b3
<< c1 << c2 << c3
<< std::endl;
}
int e1;
private:
int e2;
protected:
int e3;
};
int main()
{
D d;
std::cout << d.a1 << d.a2 << d.a3
<< d.b1 << d.b2 << d.b3
<< d.c1 << d.c2 << d.c3
<< std::endl;
E e;
std::cout << e.a1 << e.a2 << e.a3
<< e.b1 << e.b2 << e.b3
<< e.c1 << e.c2 << e.c3
<< e.d1 << e.d2 << e.d3
<< std::endl;
}
|