If the inheritance is public, then both user code and member functions of subsequently derived classes may use the derived-to-base conversion. If a class is derived using private or protected inheritance, then user code may not convert an object of derived type to a base type object. If the inheritance is private, then classes derived from the privately inherited class may not convert to the base class. If the inheritance is protected, then the members of subsequently derived classes may convert to the base type.
(1)先说用户代码中访问的问题。
B和A的关系有三种:
1 B:public A
2 B:proteced A
3 B:private A
针对这样一段代码:
A a;
B b;
a = b;
我们把它放在main.cpp中时,只有1是正确的,2,3都是错误的。这个说明的就是:只有当子类和基类的关系是public继承时,才能在用户代码中把子类赋给基类,其余两种都不行。
(2) 后继派生类中访问的问题
C和B的关系有三种
1 C:public B
2 C:proteced B
3 C:private B
但是不管C和B关系怎样,C中总是可以访问B的public和protected成员,现在假设C中有一个成员函数
void C::func()
{
A a;
B b;
a = b;
}
此时当B和A的关系是public,protected继承的时候,函数func的这段代码都没有问题,因为A,B中的非private成员在C中都可以为访问,所以没有问题。但是当B和A的关系是private的时候,这段代码就出问题了,因为A在B中是私有成员,所以不能访问A,更不用说 a = b了。