必看!用示例代码学 C++ 继承,快速掌握基础知识,高效提升编程能力

C++继承


目录

C++继承

●1.继承的概念及定义

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

●3.继承中的作用域

●4.子类的默认成员函数

●5.继承与友元

●6.继承与静态成员

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

●8.继承的总结和反思


1.继承的概念及定义

继承机制是面向对象程序设计使代码可以复用的最重要的手段,它允许程序员在保持原有类特性的基础上进行扩展,增加功能,这样产生新的类,称派生类。

示例:

c++ 复制代码
class person
{
public:
    void show_info() //父类的公共功能函数,可以被其子类继承使用;
    {
        cout << "name:" << this->_name << endl;
        cout << "age:" << this->_age << endl;
    }
protected:
    //父类中的成员变量,子类同样可以继承到,但是需要注意前提为public或protected;
    string _name;
    int _age;
};
class student : public person    //class 派生类(子类):继承方式 基类(父类)
{
public:
    student(string name = "xxx", int age = 0, int id = 0)
    {
        _name = name;
        _age = age;
        stud_id = id;
    }
protected:
    int stud_id;
};
class teacher : public person    //class 派生类(子类):继承方式 基类(父类)
{
public:
    teacher(string name = "xxx", int age = 0, int id = 0)
    {
        _name = name;
        _age = age;
        teac_id = id;
    }
protected:
    int teac_id;
};
void test1()
{
    student s("zs", 20, 1001);
    s.show_info();
    teacher t("ls", 30, 2001);
    t.show_info();
}
  1. 基类private成员在派生类中无论以什么方式继承都是不可见的。这里的不可见是指基类的私有成员还是被继承到了派生类对象中,但是语法上限制派生类对象不管在类里面还是类外面都不能去访问它。
  2. 基类private成员在派生类中是不能被访问,如果基类成员不想在类外直接被访问,但需要在派生类中能访问,就定义为protected。可以看出保护成员限定符是因继承才出现的。
  3. 实际上面的表格我们进行一下总结会发现,基类的私有成员在子类都是不可见。基类的其他成员在子类的访问方式 == Min(成员在基类的访问限定符,继承方式),public > protected> private。
  4. 使用关键字class时默认的继承方式是private,使用struct时默认的继承方式是public,不过最好显示的写出继承方式。
  5. 在实际运用中一般使用都是public继承,几乎很少使用protetced/private继承,也不提倡使用protetced/private继承,因为protetced/private继承下来的成员都只能在派生类的类里面使用,实际中扩展维护性不强。

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

派生类对象可以赋值给基类的对象 / 基类的指针 / 基类的引用。这里有个形象的说法叫切片或者切割。寓意把派生类中父类那部分切来赋值过去。而基类对象不可以赋值给派生类。

示例:

c++ 复制代码
class person
{
public:
    void show_info()
    {
        cout << "name:" << this->_name << endl;
        cout << "age:" << this->_age << endl;
    }
protected:
    string _name;
    int _age;
};
class student : public person    //class 派生类(子类):继承方式 基类(父类)
{
public:
    student(string name = "xxx", int age = 0, int id = 0)
    {
        _name = name;
        _age = age;
        stud_id = id;
    }
protected:
    int stud_id;
};
void test2()
{
    //1.子类(派生类)可以赋值给父类(基类) 对象/指针/引用
    student sobj;
    person pobj=sobj;
    person *p_pobj=&sobj;
    person &i_pobj=sobj;
 
    //2.父类不可以赋值给子类
    sobj=pobj;//error报错
}

3.继承中的作用域

  1. 在继承体系中基类和派生类都有独立的作用域。
  2. 子类和父类中有同名成员,子类成员将屏蔽父类对同名成员的直接访问,这种情况叫隐藏,也叫重定义。(在子类成员函数中,可以使用 基类::基类成员 显示访问)
  3. 需要注意的是如果是成员函数的隐藏,只需要函数名相同就构成隐藏。
  4. 注意在实际中在继承体系里面最好不要定义同名的成员。

示例:成员变量重定义

c++ 复制代码
class person
{
public:
protected:
    int sex = 0; //隐藏
};
class student : public person
{
public:
    student(string name = "xxx", int age = 0, int sex = 0)
    {
        _name = name;
        _age = age;
        _sex = sex;
    }
    void show_info()
    {
        cout << "name:" << this->_name << endl;
        cout << "age:" << this->_age << endl;
        cout << "sex:" << this->_sex << endl;
    }
protected:
    string _name;
    int _age;
    int _sex; //与父类中的成员变量同名
};
 
void test3()
{
    student s("ww",20,1);
    s.show_info();
}
//name:ww
//age:20
//sex:1

示例:成员函数重定义

c++ 复制代码
class person
{
public:
    void show_info() //隐藏
    {
        cout << "sex:" << this->_sex << endl;
    }
protected:
    int _sex = 18;
};
class student : public person
{
public:
    void show_info() //与父类中的成员函数同名
    {
        cout << "name:" << this->_name << endl;
        cout << "age:" << this->_age << endl;
    }
protected:
    string _name="zs";
    int _age=20;
};
 
void test4()
{
    student s;
    s.show_info();
}
//name:zs
//age:20

4.子类的默认成员函数

  1. 派生类的构造函数必须调用基类的构造函数初始化基类的那一部分成员。如果基类没有默认的构造函数,则必须在派生类构造函数的初始化列表阶段显示调用。
  2. 派生类的拷贝构造函数必须调用基类的拷贝构造完成基类的拷贝初始化。
  3. 派生类的operator=必须要调用基类的operator=完成基类的复制。
  4. 派生类的析构函数会在被调用完成后自动调用基类的析构函数清理基类成员。因为这样才能保证派生类对象先清理派生类成员再清理基类成员的顺序。
  5. 派生类对象初始化先调用基类构造再调派生类构造。
  6. 派生类对象析构清理先调用派生类析构再调基类的析构。

示例:

c++ 复制代码
class person{
public:
    person(const string name)//构造函数,进行对象成员的初始化
        :_name(name)
    {
        cout<<"person(const string name)构造函数"<<endl;
    }
 
    person(const perosn &p)//拷贝构造函数,person p1(p);
    {
        _name=p._name;
        cout<<"    person(const perosn &p)拷贝构造函数"<<endl;
    }
 
    person& operator=(const perosn &p)//赋值函数,person p1=p;
    {
        if(this!=&p)
        {
            this._name=p._name;
        }
        cout<<"person& operator=(const perosn &p)赋值函数"<<endl;
        return *this;
    }
 
    ~person()//析构函数
    {
        cout<<"    ~person()析构函数"<<endl;
    }
protected:
    string _name;
};
class student:public person{
public:
    student(const string name="xxx",int num=1000) //构造函数(缺省)
        :person(name),_num(num)
    {
        cout<<"student(const string name,int num)构造函数"<<endl;
    }
 
    student(const student &s)//拷贝构造函数
    {
        person(s); //子类可以拆解赋值给父类
        _num=p._num;
        cout<<"student(const student &s)拷贝构造函数"<<endl;
    }
 
    student& operator=(const student &s)//赋值函数
    {
        if(this!=&s)
        {
            person::operator=(s);//具有难度
            _num=s._num;
        }
        cout<<"student& operator=(const student &s)赋值函数"<<endl;
        return *this;
    }
 
    void show_info()
    {
        cout<<this._name<<" "<<this._num<<endl;
    }
 
    ~student()//析构函数
    {
        cout<<"~student()析构函数"<<endl;
    }
private:
    int _num;
};
 
void test5()
{
    student s1("zs",1001);
    student s2(s1);
    student s3=s1;
    s1.show_info();
    s2.show_info();
    s3.show_info();
}

5.继承与友元

友元机制允许特定函数或类去访问另一个类的私有或保护成员,且友元关系不可以继承。

示例:

c++ 复制代码
class student;
class person{
public:
    friend void display(const person& p,const student &s);
protected:
    string _name;
};
class student:public person{
protected:
    int _num;
};
void display(const person& p,const student &s)
{
    //不将该函数友元化后,类外函数是无法去访问类内私有和保护成员变量
    cout<<p._name<<endl;
    cout<<s._num<<endl;
}
 
void test6()
{
    person p;
    student s;
    display(p,s);
}

6.继承与静态成员

基类定义了static静态成员,则整个继承体系里面只有一个这样的成员。无论派生出多少个子类,都只有一个static成员实例 。且static静态成员使用的方法比较特殊,需要在类内声明,在类外定义。

示例:

c++ 复制代码
class person{
public:
    static int _count; //声明
public:
    person()
    {
        _count++;
    }
protected:
    string _name;
};
int person::_count=0; //定义
 
class student:public person{
public:
protected:
    int _num;
};
class graduate:public student{
public:
protected:
    string _finaldesign;
};    
//上述继承模式为单继承,graduate->student->person
 
void test7()
{
    student s1;
    student s2;
    student s3;
    graduate g1;
    cout<<person::_count<<endl;//其使用方法为: 作用域::静态成员变量
}

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

菱形继承的问题:从下面的对象成员模型构造,可以看出菱形继承有数据冗余和二义性的问题。在Assistant的对象中Person成员会有两份。

示例:

c++ 复制代码
class person{
public:
    string _name;
};
class student:public person{
public:
protected:
    int _num;
};
class teacher:public person{
public:
protected:
    int _id;
};    
class assistant:public student,public teacher{
public:
protected:
    string _majorCourse;
};
 
void test8()
{
    //1.这样使用会有二义性,无法明确访问的是哪一个所属父类的_name
    assistant a;
    a._name="zs";
    //2.需要显示指定访问哪个父类的成员,从而解决了数据二义性的问题,但无法解决数据冗余的问题
    a.student::_name="xxx";
    a.teacher::_name="yyy";
}

虚拟继承可以解决菱形继承的二义性和数据冗余的问题。如上面的继承关系,在student和teacher的继承person时使用虚拟继承,即可解决问题。需要注意的是,虚拟继承不要在其他地方去使用。

示例:

c++ 复制代码
class person{
public:
    string _name;
};
class student:virtual public person{ //虚拟继承person父函数
public:
protected:
    int _num;
};
class teacher:virtual public person{ //虚拟继承person父函数
public:
protected:
    int _id;
};    
class assistant:public student,public teacher{
public:
protected:
    string _majorCourse;
};
 
void test9()
{
    //这样使用无二义性
    assistant a;
    a._name="zs";
}

8.继承的总结和反思

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

示例:

c++ 复制代码
//has-a的组合关系
class Tire{
protected:
    string _tbrand="michelin";    //品牌
    size_t _size=17;    //尺寸
};
class Car{
protected:
    string _cbrand="Benz";//品牌
    string _colour="white";//颜色
    string _num="xxxxxx";//车牌
    Tire _t;    //轮胎(类的组合)
};

<您的三连和关注是我最大的动力>
🚀 文章作者:张同学的IT技术日记
分类专栏:C++系列

相关推荐
SimonKing3 分钟前
Spring Boot Admin:一站式监控微服务,这个运维神器真香!
java·后端·程序员
uhakadotcom13 分钟前
如何安装和使用开源的Meilisearch
后端·面试·github
高松燈16 分钟前
自动拆箱 导致的空指针问题复盘
后端
IT_陈寒39 分钟前
Java性能优化实战:5个立竿见影的技巧让你的应用提速50%
前端·人工智能·后端
陈随易2 小时前
10年老前端,分享20+严选技术栈
前端·后端·程序员
汪子熙2 小时前
计算机世界里的 blob:从数据库 BLOB 到 Git、Web API 与云存储的二进制宇宙
后端
鞋尖的灰尘2 小时前
springboot-事务
java·后端
元元的飞2 小时前
6、Spring AI Alibaba MCP结合Nacos自动注册与发现
后端·ai编程
Cisyam2 小时前
Go环境搭建实战:告别Java环境配置的复杂
后端
六月的雨在掘金2 小时前
狼人杀法官版,EdgeOne 带你轻松上手狼人杀
前端·后端