C++:类继承之基类和派生类(第十三章)

概念:
基类是爸爸类,派生类是儿子类,派生类可以拥有基类原有的特征包括数据和方法。

1. 首先创建一个person基类,使用简单功能

/类声明
class Person
{
        string first_n;
        string last_n;
        bool athome;
        
    public:
        Person(const string& s1="none",const string& s2="none",
                bool ah = false);
        void Name() const;
        bool Athome() const {return athome;}
        void Resetperson(bool v){athome = v;}
 } ;

/源代码文件
Person::Person(const string&s1,const string& s2, bool ah):first_n(s1),last_n(s2),athome(ah)
{}

void Person::Name() const
{
    std::cout<<first_n<<","<<last_n;
}

程序解析:

  1. Person构造函数参数是string引用,然后使用初始化成员列表来初始化,比较高大上。关于参数是string引用还是const char* ,往下拉。
    基类没什么难度,已经老熟人了。

2. 派生类:在基类的基础上多一些数据及其他一些功能
派生类的声明:class APerson :public Person 一个冒号、一个public+基类说明APerson是Person的派生类

  1. 完成以上工作,派生类有如下特点
  • 派生类存储了基类的数据和方法(继承了实现和接口)
  1. 派生类需要添加的:
  • 派生类需要有自己的构造函数,可以添加额外数据和成员函数
/类声明:
class APerson : public Person
 {
        int age;        
    public:
        APerson(int a=0,const string& s1="none",
                const string& s2="none",bool ah = false);
        APerson(int a, const Person& ps);

        int Age() const{return age;}
        void ResetAPerson(int a){age = a;}
 };

/源代码文件:
APerson::APerson(int a,const string& s1,const string& s2,bool ah):Person(s1,s2,ah)
{
    age =a;
}

APerson::APerson(int a,const Person& ps):Person(ps),age(a)
{
}

程序解析:

  1. 派生类不能直接访问基类的私有成员,必须通过基类的成员函数进行访问。也就是说,派生类的构造函数必须使用基类的构造函数。
    其中Person(s1,s2,ah)调用了Person的构造函数;
    Person(ps)调用了Person的复制构造函数(因为没有使用到动态内存分配啥的所以默认的复制构造函数就得行了,复制基类数据到基类数据 )
  2. 有关析构函数的调用,显式调用派生类析构函数再调用基类析构函数。
/main.cpp
#include"person.h"
#include<iostream>
using std::cout;
using std::endl;

int main()
{
    Person p1("Zhang","Jeff",false);
    APerson p2(20,"Li","SB",true);
    p1.Name();
    if(p1.Athome())
        cout<<" is at home\n";
    else
        cout<<" is not at home"<<endl;
    p2.Name();
    if(p2.Athome())
        cout<<" is at home\n";
    else
        cout<<" is not at home"<<endl;
    APerson p3(19,p1) ;
    p3.Name();
    cout<<" is "<<p3.Age()<" years old\n" ;
    p2.Name();
    cout<<" is "<<p2.Age()<<" years old \n";
}

结果如下:

image.png

派生类和基类之间的特殊关系:

  1. 派生类对象可以使用基类的方法
  2. 基类指针和引用可以在不进行显式类型转换的情况下指向派生类对象。因为派生类对象包含了所以基类对象的数据和方法。
  3. 派生类指针或引用不可以指向基类对象,因为派生类有基类没有的数据或方法。
/main.cpp
void show_quote( Person& p)
{
    p.Name();
    if(p.Athome())
        cout<<" is at home\n";
    else
        cout<<" not at home\n";
}

void show_ptr( Person* p)
{
    p->Name();
    if(p->Athome())
        cout<<" is at home\n";
    else
        cout<<" not at home\n";
}

    Person p4("Mao","Zedong",true);
    APerson p5(100,"Xi","Jinping",false);
    show_quote(p4);
    show_ptr(&p4); //注意参数为指针要传递地址
    show_quote(p5);
    show_ptr(&p5);

image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。