c++中公共继承、私有继承和受保护继承之间的区别是什么?
我在SO上找到的所有问题都是针对具体案例的。
c++中公共继承、私有继承和受保护继承之间的区别是什么?
我在SO上找到的所有问题都是针对具体案例的。
当前回答
它本质上是派生类中基类的公共和受保护成员的访问保护。通过公共继承,派生类可以看到基类的公共成员和受保护成员。而私有继承则不能。使用protected,派生类及其派生的任何类都可以看到它们。
其他回答
1)公共继承:
a.基类的私有成员在派生类中不可访问。
b.基类的受保护成员在派生类中仍然受保护。
c.基类的公共成员在派生类中保持为公共。
因此,其他类可以通过派生类对象使用基类的公共成员。
2)受保护遗产:
a.基类的私有成员在派生类中不可访问。
b.基类的受保护成员在派生类中仍然受保护。
c.基类的公共成员也成为派生类的受保护成员。
因此,其他类不能通过派生类对象使用基类的公共成员;但它们可用于派生的子类。
3)私人继承:
a.基类的私有成员在派生类中不可访问。
b.基类的Protected & public成员变成派生类的private成员。
因此,基类的成员不能被其他类通过派生类对象访问,因为它们在派生类中是私有的。甚至是Derived的子类 类不能访问它们。
简介:
Private:除了类内部,没有人可以看到它 Protected: Private +派生类可以看到它 公众:全世界都能看到
在继承时,你可以(在某些语言中)在某个方向上改变数据成员的保护类型,例如从protected变为public。
它与基类的公共成员如何从派生类中公开有关。
Public——>基类的Public成员为Public(通常为默认值) Protected ->基类的公共成员将受到保护 Private ->基类的public成员为Private
As litb points out, public inheritance is traditional inheritance that you'll see in most programming languages. That is it models an "IS-A" relationship. Private inheritance, something AFAIK peculiar to C++, is an "IMPLEMENTED IN TERMS OF" relationship. That is you want to use the public interface in the derived class, but don't want the user of the derived class to have access to that interface. Many argue that in this case you should aggregate the base class, that is instead of having the base class as a private base, make in a member of derived in order to reuse base class's functionality.
任何继承自您的类的类都可以访问受保护的数据成员。但是,私有数据成员不能。假设我们有以下内容:
class MyClass {
private:
int myPrivateMember; // lol
protected:
int myProtectedMember;
};
从扩展到这个类,引用这个。myPrivateMember不能工作。然而,这。myProtectedMember意志。这个值仍然是封装的,所以如果我们有一个myObj类的实例化,那么myObj。myProtectedMember不能工作,所以它的功能类似于私有数据成员。
它本质上是派生类中基类的公共和受保护成员的访问保护。通过公共继承,派生类可以看到基类的公共成员和受保护成员。而私有继承则不能。使用protected,派生类及其派生的任何类都可以看到它们。