[Fun with c++] Inheritance depth analysis

Topic of this issue: In-depth Analysis of Inheritance

Blog homepage: Xiaofeng

Share what you have learned and the problems you have encountered

The ability of the editor is limited, and if there are mistakes, I hope everyone will give me a lot of help.

  1. The concept and definition of inheritance

1.1 The concept of inheritance

Inheritance (inheritance) mechanism is the most important method for object-oriented programming to make code reusable. It allows programmers to expand and add functions while maintaining the characteristics of the original class, thus generating new classes, called derived classes. Inheritance presents the hierarchical structure of object-oriented programming, reflecting the cognitive process from simple to complex. The reuse we have been exposed to before is function reuse, and inheritance is the reuse of class design levels .

class Person
{
public:
 void Print()
 {
    cout << "name:" << _name << endl;
    cout << "age:" << _age << endl;
 }
protected:
 string _name = "peter"; // 姓名
 int _age = 18;  // 年龄
};

// 继承后父类的Person的成员(成员函数+成员变量)都会变成子类的一部分。
// 这里体现出了Student和Teacher复用了Person的成员。
// 我们使用监视窗口查看Student和Teacher对象,可以看到变量的复用。
// 调用Print可以看到成员函数的复用。
class Student : public Person
{
protected:
    int _stuid; // 学号
};
class Teacher : public Person
{
protected:
    int _jobid; // 工号
};

1.2 Inheritance definition

1.2.1 Definition format

Below we see that Person is the parent class, also known as the base class. Student is a subclass, also known as a derived class .

1.2.2 Inheritance and access qualifiers

1.2.3 Changes in access methods of inherited base class members

Summarize:
1. The private members of the base class are invisible no matter how they are inherited in the derived class. The invisible here refers to the private members of the base class, but they are still inherited into the derived class object, but the derived class object is grammatically restricted from accessing it no matter whether it is inside or outside the class .
2. The private members of the base class cannot be accessed in the derived class. If the base class member does not want to be accessed directly outside the class, but needs to be accessible in the derived class, it is defined as protected. It can be seen that the protected member qualifier is due to inheritance.
3. In fact, if we summarize the above table, we will find that the private members of the base class are not visible in the subclass. The access method of other members of the base class in the subclass == Min (access qualifier of the member in the base class, inheritance method), public > protected > private.
4. 使用关键字class时默认的继承方式是private,使用struct时默认的继承方式是public,不过 最好显示的写出继承方式。
5. 在实际运用中一般使用都是public继承 ,几乎很少使用protetced/private继承,也不提倡 使用protetced/private继承,因为protetced/private继承下来的成员都只能在派生类的类里 面使用,实际中扩展维护性不强。

  1. 基类和派生类对象赋值转换

派生类对象 可以 赋值给 基类的对象 / 基类的指针 / 基类的引用 。这里有个形象的说法叫切片 或者切割。 寓意把派生类中父类那部分切来赋值过去 .
基类对象不能赋值给派生类对象.
基类的指针或者引用可以通过强制类型转换赋值给派生类的指针或者引用。但是必须是基类 的指针是指向派生类对象时才是安全的。 这里基类如果是多态类型,可以使用RTTI(RunTime Type Information)的dynamic_cast 来进行识别后进行安全转换。(后面我在多态会写到)
void test()
{
    Person p;
    Student s;

    p = s;//中间不存在类型转换
    Person& rp = s;//不加const也可以。
    //rp是子类当中父类那一部分的别名。
    rp._age++;
    rp._name = "zhang";
    Person* pp = &s;
    //指向子类当中父类那一部分
    pp->_age++;
    pp->_name = "gao";
    int i = 1;
    double d = 2.2;
    i = d;//中间会产生临时变量,且临时变量具有常属性。
    //int& ri = d;//会报错
    //因为临时变量具有常属性,所以这里要加const 类型才可以
    const int& ri = d;
}

通过调试窗口可以观察:

3.继承中的作用域

1. 在继承体系中基类和派生类都有独立的作用域.
2. 子类和父类中有同名成员, 子类成员将屏蔽父类对同名成员的直接访问 ,这种情况叫隐藏, 也叫重定义。(在子类成员函数中, 可以使用 基类::基类成员 显示访问
3. 需要注意的是如果是成员函数的隐藏,只需要函数名相同就构成隐藏。(与函数的参数无关)
4. 注意在实际中在继承体系里面最好不要定义同名的成员。
// Student的_num和Person的_num构成隐藏关系,可以看出这样代码虽然能跑,但是非常容易混淆
class Person
{
public:
    void fun()//父类中的fun就被隐藏了
    {
        cout << "person::fun" << endl;
    }
protected:
    string _name = "小李子"; // 姓名
    int _num = 111;   // 身份证号
};
class Student : public Person
{
public:
    void fun(int i)
    {
        cout << i << endl;
        cout << "student::fun" << endl;
    }
    void Print()
    {
        cout << " 姓名:" << _name << endl;
        cout << " 身份证号:" << Person::_num << endl;
        //父类中的_num 就被隐藏了。需要指定作用域访问。
        cout << " 学号:" << _num << endl;
    }
protected:
    int _num = 999; // 学号
};


void Test()
{
    Student s1;
    s1.Print();

    //父类和子类中的fun()构成隐藏/重定义。
    //不是重载
    s1.fun(1);//访问的是子类中的fun函数。

    //s1.fun();
    //这里汇编报错(缺少参数),不会访问父类中的fun函数(被影藏了)。
    //虽然编译报错但是也是构成隐藏.
    //想要访问到需要指定作用域。
    s1.Person::fun();
};

4.派生类的默认成员函数

6个默认成员函数,“默认”的意思就是指我们不写,编译器会变我们自动生成一个,那么在派生类 中,这几个成员函数是如何生成的呢?

1. 派生类的构造函数必须调用基类的构造函数初始化基类的那一部分成员。如果基类没有默认 的构造函数,则必须在派生类构造函数的初始化列表阶段显示调用。
2. 派生类的拷贝构造函数必须调用基类的拷贝构造完成基类的拷贝初始化
3. 派生类的operator=必须要调用基类的operator=完成基类的复制。
4. 派生类的析构函数会在被调用完成后自动调用基类的析构函数清理基类成员。 因为这样才能 保证派生类对象先清理派生类成员再清理基类成员的顺序.
5. 子类对象初始化先调用父类构造再调子类构造。
6. 子类对象析构清理先调用子类析构再调父类的析构。
7. 因为后续一些场景析构函数需要构成重写,重写的条件之一是函数名相同(这个我们后面会讲 解)。那么编译器会对析构函数名进行特殊处理,处理成destrutor()所以父类析构函数不加 virtual的情况下,子类析构函数和父类析构函数构成隐藏关系.

注意子类的父类的构造析构顺序: 是父类先构造,子类先析构.

class Person
{
public:
    Person(const char* name = "peter")
        : _name(name)
    {
        cout << "Person()" << endl;
    }

    Person(const Person& p)
        : _name(p._name)
    {
        cout << "Person(const Person& p)" << endl;
    }

    Person& operator=(const Person& p)
    {
        cout << "Person operator=(const Person& p)" << endl;
        if (this != &p)
            _name = p._name;

        return *this;
    }

    ~Person()
    {
        cout << "~Person()" << endl;
    }
protected:
    string _name; // 姓名
};
class Student : public Person
{
public:
    //构造
    Student(const char* name, int num)
        : Person(name)//这里就是要调用父类的构造函数
        , _num(num)
    {
        cout << "Student()" << endl;
    }

    //拷贝构造
    Student(const Student& s)
        : Person(s)//s切片过去的
        , _num(s._num)
    {
        cout << "Student(const Student& s)" << endl;
    }

    //赋值
    Student& operator = (const Student& s)
    {
        cout << "Student& operator= (const Student& s)" << endl;
        if (this != &s)
        {
            Person::operator =(s);//显示的调用 operator=
            //子类的operator=  和 父类的 operator= 构成了隐藏,
            //所以需要显示调用。
            _num = s._num;
        }
        return *this;
    }

    //析构函数
    //子类析构函数和父类析构函数构成隐藏(由于多态的关系需求,所有的析构函数都会被特殊处理成destructor函数)
    //析构函数不需要我们自己调用。因为他要保证子类先析构,父类再析构。

    ~Student()
    {
        //这里不用自己调用,编译器会自己去调用 ~Person();
        
        //当然我们也可也自己调用
       // Person::~Person();
        //注意:这里我们自己调用了一次,但是它还是会再调用一次(编译器的默认行为)
        //所以一般不写,让编译器自己调用即可。防止多重析构。
        cout << "~Student()" << endl;
    }

protected:
    int _num; //学号
};

5.继承与友元

友元关系不能继承,也就是说基类友元不能访问子类私有和保护成员.
class Student;
class Person
{
public:
    friend void Display(const Person& p, const Student& s);
protected:
    string _name="zhang"; // 姓名
};
class Student : public Person
{
protected:
    int _stuNum = 1000; // 学号
};
void Display(const Person& p, const Student& s)
{
    cout << p._name << endl;
    //cout << s._stuNum << endl;
    //无法访问子类的私有成员(_stuNum),说明不是友元函数。
    //这种友元关系没有被继承下去。
}
void main()
{
    Person p;
    Student s;
    Display(p, s);
}

6.继承与静态成员

基类定义了static静态成员,则整个继承体系里面只有一个这样的成员。无论派生出多少个子 类,都只有一个static成员实例 。

class Person
{
public:
    static int _count;
    string _name="zhang"; // 姓名

    void print()
    {
        cout << "person::print" << endl;
    }
};
int Person::_count = 0;

class Student : public Person
{
protected:
    int _stuNum = 1000; // 学号
};

int main()
{
    Person p;
    Student s;

    cout << p._count++ << endl;    //0
    cout << s._count <<endl;//1

    cout << &p._count << endl;//010103DC
    cout << &s._count << endl;//010103DC
    //静态成员属于整个类,所有对象,同时也属于所有派生及对象

    cout << Person::_count << endl;//1
    cout << Student::_count << endl;//1


    //讲个特例
    Person* ptr = nullptr;
    //cout << ptr->_name << endl;//这个肯定不可以
    //这是空指针的解引用。非法。

    ptr->print();//这个可以
    //这个看似是ptr解引用了,但是实际上没有解引用。
    //底层
    //但是如果print函数内部访问了成员变量就立马报错,this指针解引用了。

    cout<< ptr->_count<< endl;//这个也可以


    //下面这俩和上面 -> 相同的道理 (下图有汇编 完全相同),不要被蒙蔽了双眼。
    (*ptr).print();
    cout << (*ptr)._count << endl;


    //因为成员函数放在代码段
    //static成员在静态区
    //成员变量在栈区,没有可比性.


    return 0;
}
ptr->print() 和 (*ptr).print() 底层汇编

7.复杂的菱形继承及菱形虚拟继承

单继承:一个子类只有一个直接父类时称这个继承关系为单继承.

多继承:一个子类有两个或以上直接父类时称这个继承关系为多继承
菱形继承:菱形继承是多继承的一种特殊情况。
菱形继承有很大的问题,会引发 数据冗余和二义性.
Assistant的对象中Person成员会有两份。

class person
{
public:
    string _name = "zhang";//名字
    int _id = 420;//身份证号
};

class student : public person
{
public:
    int _stunum;//学号
};

class teacher : public person
{
public:
    int _jodnum;//职工号

};

class  course : public student, public teacher
{
public:
    int _course;//课程
};

int main()
{
    course c;
    //数据冗余和二义性。
    //cout<<c._id << endl;
    报错:course::_id 不明确

    //可以直接指定它。//这样是没有问题的。
    cout << c.person::_id << endl;
    cout << c.student::_id << endl;
    //但是还是没有解决数据冗余
    return 0;
}
虚拟继承 可以解决菱形继承的二义性和数据冗余的问题。如上面的继承关系,在Student和 teacher的继承Person时使用虚拟继承,即可解决问题。需要注意的是,虚拟继承不要在其他地 方去使用。只能在菱形继承的时候使用.
注意一定要在腰部继承.
虚继承就是为解决问题而引入的 "virtu"
class student : virtual public person
{
public:
    int _stunum;//学号
};

class teacher : virtual public person
{
public:
    int _jodnum;//职工号
};
完美解决
int main()
{
    course c;
    cout << c._name << endl;//zhang
    cout << c._id << endl;//420
    c._name = "gao";
    c._id = 4534;
    cout << c._name << endl;//gao
    cout << c._id << endl;//4534
    return 0;
}

8.虚拟继承解决数据冗余和二义性的原理

给一个实例代码:
class A
{
public:
    int _a;
};

class B : public A
{
public:
    B()
    {
        cout << "B()" << endl;
    }
    int _b;
};

class C : public A
{
public:
    C()
    {
        cout << "C()" << endl;
    }
    int _c;
};

//class D : public C, public B//先构造C 在构造B
class D : public B, public C//先构造B 在构造C
{
public:
    int _d;
};


int main()
{
    D d;
    d._b = 1;
    d._c = 2;
    d._d = 3;
    d.B::_a = 4;
    d.C::_a = 5;

    return 0;
}
调试起来观看 内存窗口.

改为虚拟继承
class B :virtual public A{
public:
    B(){cout << "B()" << endl;}
    int _b;
};

class C :virtual public A{
public:
    C(){cout << "C()" << endl;}
    int _c;
};
内存为:
菱形虚拟继承的内存对象成员模型: 这里可以分析出D对象中将A放到的了对象组成的最下 面,这个A同时属于B和C,那么B和C如何去找到公共的A呢?
这里是通过了B和C的两个指针,指 向的一张表。这两个指针叫虚基表指针,这两个表叫虚基表。虚基表中存的偏移量。通过偏移量 可以找到下面的A。

D的模型
B的模型

9.继承的总结和反思

9.1.总结

1. 很多人说C++语法复杂,其实多继承就是一个体现。有了多继承,就存在菱形继承,有了菱 形继承就有菱形虚拟继承,底层实现就很复杂。 所以一般不建议设计出多继承,一定不要设 计出菱形继承。否则在复杂度及性能上都有问题。
2. 多继承可以认为是C++的缺陷之一,很多后来的语言都没有多继承,如Java.

9.2.继承和组合的问题

public继承是一种is-a的关系也就是说每个派生类对象都是一个基类对象。 组合是一种has-a的关系。 假设B组合了A,每个B对象中都有一个A对象.
class A{
    int _a;
};
//继承
class C: public A{
    int _c;
};
//组合
class B{
    A _t;
};
继承允许你根据基类的实现来定义派生类的实现。这种通过生成派生类的复用通常被称 为 白箱复用 (white-box reuse)。术语“白箱”是相对可视性而言:在继承方式中,基类的 内部细节对子类可见 。 继承一定程度破坏了基类的封装,基类的改变,对派生类有很 大的影响。派生类和基类间的依赖关系很强,耦合度高。
对象组合是类继承之外的另一种复用选择。新的更复杂的功能可以通过组装或组合对象 来获得。对象组合要求被组合的对象具有良好定义的接口。这种复用风格被称为 黑箱复 用 (black-box reuse), 因为对象的内部细节是不可见的。对象只以“黑箱”的形式出现。 组合类之间没有很强的依赖关系,耦合度低。优先使用对象组合有助于你保持每个类被 封装。
实际尽量多去用组合。组合的耦合度低,代码维护性好 。不过继承也有用武之地的,有 些关系就适合继承那就用继承,另外要实现多态,也必须要继承。 类之间的关系可以用 继承,可以用组合,就用组合。

10.经典问题

1. 什么是菱形继承?菱形继承的问题是什么?
2. 什么是菱形虚拟继承?如何解决数据冗余和二义性的? 3. 继承和组合的区别?什么时候用继承?什么时候用组合?

Guess you like

Origin blog.csdn.net/zxf123567/article/details/129505439