(12) C ++ inheritance

  

1 inheritance syntax

class Base {
public:
    void print() {
        cout << "Base" << endl;
    }
};

class Sun : public Base {

};

int main() {
    Sun s;
    s.print();
}

 

2 inherit the access rights

 When the subclass inherits the parent class, will change the access permissions are inherited according to a member of a subclass inherits three ways

 

3. inheritance model

All member variables and functions are subclasses of the parent class inheritance, but some can not be invoked in accordance with different permissions

View:

(1) Open a command prompt developers

Open windows from the start

 

 (2) Go to File Path

(3) cl / d1 reportSingleClassLayout class file name

cl /d1 reportSingleClassLayoutSun main.cpp

Note: When the back c letters L, d is a number one behind

class Base {
public:
    int a;
    void print() {
        cout << "Base" << endl;
    }
};

class Sun : public Base {
    int b;
}

 

 

 You can see the members in the class is inherited down

 4. succession constructor and destructor sequence

 

class Base {
 public : 
    Base () { 
        COUT << " parent structure " << endl; 
    }
     ~ Base () { 
        COUT << " parent destructor " << endl; 
    } 
}; 

class the Sun: public Base {
 public : 
    the Sun () { 
        COUT << " construction of subclasses " << endl; 
    }
     ~ the Sun () { 
        COUT << " sub-class destructor " << endl;
    }
};

int main() {
    {
        Sun s;
    }
}

 

 Life cycle in line with the way the stack

The call parent class and subclass

Subclass if you want to call member variables or member of the parent class need to increase the scope

 

class Base {
 public :
     void Print () { 
        COUT << " parent " << endl; 
    } 
}; 

class the Sun: public Base {
 public :
     void Print () { 
        COUT << " subclasses " << endl; 
    } 
} ; 

int main () { 
    { 
        the Sun S; 
        s.print (); 
        s.Base :: Print (); // subclass parent objects need to add scope 
    } 
}

 

Static rules are the same

 

5. Multiple Inheritance

class Base1 {
public:
    void print() {
        cout<<"父类1"<<endl;
    }
};

class Base2 {
public:
    void print() {
        cout << "父类2" << endl;
    }
};

class Sun : public Base1, public Base2{
public:
    void print() {
        cout << "子类" << endl;
    }
};

 Carefully situation appears different parent of the same name

 

Guess you like

Origin www.cnblogs.com/buchizaodian/p/11606102.html