C ++ inherited basis

Before learning inheritance, we must first have a more understanding of the class may not be familiar with the look here

Inheritance is where the essence of a large C ++, but has also inherited the difficulties, this introduction from the base portion.

Inheritance relationship is probably this:

 

 

 "Father" on FIG class is called a base class, a parent class or superclass

 The figure of "children" and "grandchildren" and more "children and grandchildren" of the class may appear is called a subclass

And this is called the structure diagram: inheritance hierarchy

 When writing inherited management structure diagram must first come out, come out analysis.

These theories must first clear rationale, then realized

 

In order to better understand ideas I use win32 window on the Windows platform to give an example of a similar inheritance:

(Note: win32 programming window is not inherited , but can be analyzed by the inheritance hierarchy )

 

 

 In the inheritance hierarchy, we must pay attention to the direction of the arrow , noted by subclass -> parent class , not the parent class -> subclass

Inheritance has the following basic characteristics:

  1. inheritance subclasses of the parent class can access public, protected data members, but may not access the private section (subclasses and can modify the public has access to the parent class's data members protected)

  2. When inherited subclass to access the data in the parent class, but no access to the parent class subclass (shown above the arrow)

  3. succession when the pointer or reference to be converted to the parent class subclass, truncation phenomenon occurs

  4. 继承具有多态性

 

首先解释一下:

 1. 数据截断可以理解为当发生子类的引用或指针转父类时, 子类中独有的数据将会全部丢失

 2. 多态性其实就是在解释上面的第1点, 也就是子类不仅具有父类的数据, 也可以有自己的独有的数据

 

现在尝试编写继承: 

 

class Basic
{
    string myPrivate="Private";
    protected:
        string myProtected="Protected";
    public:
        string myPublic="Public";
};
class Child: public Basic //继承一个类的表示方法
{
    public:
        void getMembers()
        {
            cout<<myPublic<<endl;//Worked
            cout<<myProtected<<endl;//Worked
            cout<<myPrivate<<endl;//Error!
        }
};
int main()
{
    Child child;
    child.getMembers();
    return 0;
}

 

 

 

实践表明, private无法访问.

 

有关继承的基础部分已结束, 请等待更新.

Guess you like

Origin www.cnblogs.com/tweechalice/p/12205737.html