• C++学习:类继承


    面相对象的主要目的之一就是提供可重用的代码。

    类继承就是从已有的类派生出新的类,而派生类继承了原有类,也就是基类的特征和成员函数。

    继承一笔财富比自己白手起家要简单的多,写代码也是一样。

    下面是可通过继承来外城的工作:

    1、可以在已有类的基础上添加新功能,例如,对于数组类,可以添加数学运算;

    2、可以给类添加数据,例如,对于数据串类,可以派生出一个类,并添加指定字符串显示颜色的数据成员;

    3、可以修改类成员函数的行为,例如给飞机乘客提供服务的Passenger类,可以派生出提供头等舱服务FirstClassPassenger类。

    一个简单的基类

    从一个类派生出另一个类时,原始类称为基类,继承类称为派生类

    webtown俱乐部决定统计乒乓球会会员,俱乐部的程序员需要设计一个简单的TableTennisPlayer类

    1. #ifndef TABLETENNISPLAYER_H
    2. #define TABLETENNISPLAYER_H
    3. #include
    4. #include
    5. using namespace std;
    6. class TableTennisPlayer
    7. {
    8. private:
    9. string firstname;
    10. string lastname;
    11. bool hasTable;
    12. public:
    13. TableTennisPlayer(const string& fn = "none", const string& ln = "none", bool ht = false);
    14. void Name() const;
    15. bool HasTable() const {return hasTable;};
    16. void ResetTable(bool v) {hasTable = v;};
    17. };
    18. #endif // TABLETENNISPLAYER_H

     

    1. #include "tabletennisplayer.h"
    2. TableTennisPlayer::TableTennisPlayer(const string& fn , const string& ln, bool ht ):firstname(fn),lastname(ln),hasTable(ht)
    3. {
    4. }
    5. void TableTennisPlayer::Name() const
    6. {
    7. cout << lastname << ", " << firstname;
    8. }

     TableTennisPlayer类只是记录会员的姓名以及是否有球桌;

    这个类是使用string类来存储姓名,比字符串数组更方便,更灵活,更安全;

    构造函数使用了成员初始化列表语法,与下面的写法等效。

    1. TableTennisPlayer::TableTennisPlayer(const string& fn , const string& ln, bool ht )
    2. {
    3. firstname = fn;
    4. lastname = ln;
    5. hasTable = ht;
    6. }

     使用前面的类

    1. #include
    2. #include "tabletennisplayer.h"
    3. int main()
    4. {
    5. TableTennisPlayer player1("Chuck", "Blizzard", true);
    6. TableTennisPlayer player2("Tara", "Boomdea", false);
    7. player1.Name();
    8. if(player1.HasTable())
    9. cout << ": has a table.\n";
    10. else
    11. cout << ": hasn't a table.\n";
    12. player2.Name();
    13. if(player2.HasTable())
    14. cout << ": has a table.\n";
    15. else
    16. cout << ": hasn't a table.\n";
    17. return 0;
    18. }

    输出结果

    1. Blizzard, Chuck: has a table.
    2. Boomdea, Tara: hasn't a table.

     派生一个类

    webtown俱乐部的一些成员曾经参加过当地的乒乓球竞标赛,需要这样一个类能包含成员在比赛中的比分。与其从0开始,不如从TableTennisPlayer类派生出来一个类。首先将RatedPlayer类声明为从TableTennisPlayer类派生而来

    1. //声明一个派生类
    2. //冒号:前面的是派生类,冒号后面的是基类
    3. //TableTennisPlayer前面的public说明它是一个公有基类
    4. //基类的私有部分称为派生类的一部分,只能通过基类的公有和保护方法去访问
    5. class RatedPlayer : public TableTennisPlayer
    6. {
    7. private:
    8. unsigned int rating;
    9. public:
    10. RatedPlayer(unsigned int r = 0, const string& fn = "none", const string& ln = "none", bool ht = false);
    11. RatedPlayer(unsigned int r, const TableTennisPlayer& tp);
    12. unsigned int Rating() const {return rating;};
    13. void ResetRating(unsigned int r) {rating = r;};
    14. };

     上面的代码完成了如下工作:

    1、派生类对象存储了基类的数据成员,也就是说派生类继承了基类的实现;

    2、派生类对象可以使用基类的方法,也就是成员函数,也叫派生类继承了基类的接口;

    因此RatedPlayer对象可以存储运动员的姓名、以及是否有球桌,另外RatedPlayer对象还可以使用TableTennisPlayer类的name()、hasTable()、ResetTable()函数。

    需要再继承特性中添加什么?

    1、派生类需要自己的构造函数;

    2、派生类可以根据需要添加额外的成员和成员函数;

    构造函数必须给次年成员和继承的成员提供数据。

    构造函数的访问权限:

    派生类不能直接访问基类的私有成员,必须通过基类的成员函数进行访问;例如,RatedPlayer构造函数不能直接设置集成的成员,如firstname、lastname、hasTable,必须使用基类的公有方法来访问私有的基类成员,也就是说派生类构造函数必须使用基类的构造函数。

    创建派生类对象时,程序首先创建基类独享,这意味着基类对象应在程序进入派生类构造函数之前被创建。C++使用成员初始化列表语法来完成这种工作。

    1. RatedPlayer::RatedPlayer(unsigned int r, const string& fn, const string& ln, bool ht):TableTennisPlayer(fn, ln, ht)
    2. {
    3. rating = r;
    4. }
    :TableTennisPlayer(fn, ln, ht)是成员初始化列表,是可执行代码,调用TableTennisPlayer构造函数

    派生类构造函数的注意事项:

    1、首先创建基类对象;

    2、派生类构造函数应通过成员初始化列表将基类信息传递给基类构造函数;

    3、派生类构造函数应初始化派生类新增的数据成员

    使用派生类

    1. #ifndef TABLETENNISPLAYER_H
    2. #define TABLETENNISPLAYER_H
    3. #include
    4. #include
    5. using namespace std;
    6. //声明一个基类
    7. class TableTennisPlayer
    8. {
    9. private:
    10. string firstname;
    11. string lastname;
    12. bool hasTable;
    13. public:
    14. TableTennisPlayer(const string& fn = "none", const string& ln = "none", bool ht = false);
    15. void Name() const;
    16. bool HasTable() const {return hasTable;};
    17. void ResetTable(bool v) {hasTable = v;};
    18. };
    19. //声明一个派生类
    20. //冒号:前面的是派生类,冒号后面的是基类
    21. //TableTennisPlayer前面的public说明它是一个公有基类
    22. //基类的私有部分称为派生类的一部分,只能通过基类的公有和保护方法去访问
    23. class RatedPlayer : public TableTennisPlayer
    24. {
    25. private:
    26. unsigned int rating;
    27. public:
    28. RatedPlayer(unsigned int r = 0, const string& fn = "none", const string& ln = "none", bool ht = false);
    29. RatedPlayer(unsigned int r, const TableTennisPlayer& tp);
    30. unsigned int Rating() const {return rating;};
    31. void ResetRating(unsigned int r) {rating = r;};
    32. };
    33. #endif // TABLETENNISPLAYER_H

     

    1. #include "tabletennisplayer.h"
    2. TableTennisPlayer::TableTennisPlayer(const string& fn , const string& ln, bool ht ):firstname(fn),lastname(ln),hasTable(ht)
    3. {
    4. }
    5. void TableTennisPlayer::Name() const
    6. {
    7. cout << lastname << ", " << firstname;
    8. }
    9. RatedPlayer::RatedPlayer(unsigned int r, const string& fn, const string& ln, bool ht):TableTennisPlayer(fn, ln, ht)
    10. {
    11. rating = r;
    12. }
    13. RatedPlayer::RatedPlayer(unsigned int r, const TableTennisPlayer& tp):TableTennisPlayer(tp), rating(r)
    14. {
    15. }

     

    1. #include
    2. #include "tabletennisplayer.h"
    3. int main()
    4. {
    5. TableTennisPlayer player1("Chuck", "Blizzard", true);
    6. RatedPlayer rplayer1(1140,"Tara", "Boomdea", false);
    7. player1.Name();
    8. if(player1.HasTable())
    9. cout << ": has a table.\n";
    10. else
    11. cout << ": hasn't a table.\n";
    12. rplayer1.Name();
    13. if(rplayer1.HasTable())
    14. cout << ": has a table.\n";
    15. else
    16. cout << ": hasn't a table.\n";
    17. cout << "name: ";
    18. rplayer1.Name();
    19. cout << " ; Rating: " << rplayer1.Rating() << endl;
    20. RatedPlayer rplayer2(1112, player1);
    21. cout << "name: ";
    22. rplayer2.Name();
    23. cout << " ; Rating: " << rplayer2.Rating() << endl;
    24. return 0;
    25. }

    输出结果

    1. Blizzard, Chuck: has a table.
    2. Boomdea, Tara: hasn't a table.
    3. name: Boomdea, Tara ; Rating: 1140
    4. name: Blizzard, Chuck ; Rating: 1112

     派生类与基类之间的特殊关系

    1、派生类的对象可以使用基类的public成员函数,

    RatedPlayer rplayer1(1140,"Tara", "Boomdea", false);
    rplayer1.Name();

    2、基类指针可以在不进行显式类型转换的情况下指向派生类对象;基类引用可以在不进行显式类型转换的情况下引用派生类对象;

    1. TableTennisPlayer& rt = rplayer1;
    2. TableTennisPlayer* pt = &rplayer2;
    3. rt.Name();
    4. pt->Name();

     但是基类指针只能用于调用基类成员函数,因此不能使用rt,pt来调用派生类ResetRating函数。

    3、不能将基类的对象和指针赋给派生类的引用和指针;

    多态公有继承

    1、在派生类中重新定义基类的方法(成员函数);

    2、使用虚函数

    银行不同支票类

    1. #ifndef BRASS_H
    2. #define BRASS_H
    3. #include
    4. using namespace std;
    5. //基类Brass
    6. //virtual 表示虚函数
    7. class Brass
    8. {
    9. private:
    10. string fullName;
    11. long acctNum;
    12. double balance;
    13. public:
    14. Brass(const string& s = "Nullboby", long an = -1, double bal = 0.0);
    15. void Deposit(double amt);
    16. virtual void Withdrow(double amt);
    17. double Balance() const;
    18. virtual void ViewAcct() const;
    19. virtual ~Brass() {};
    20. };
    21. //BrassPlus类在Brass类的基础上增加了三个私有数据成员和3个公有成员函数
    22. //BrassPlus类与Brass类都声明了ViewAcct()和Withdrow()函数,但是它们的功能是不一样的
    23. class BrassPlus : public Brass
    24. {
    25. private:
    26. double maxLoan;
    27. double rate;
    28. double owesBank;
    29. public:
    30. BrassPlus(const string& s = "Nullbody", long an = -1, double ba = 0.0, double ml = 500, double r = 0.11125);
    31. BrassPlus(const Brass& ba, double ml = 500, double r = 0.11125);
    32. virtual void ViewAcct() const;
    33. virtual void Withdrow(double amt);
    34. void ResetMax(double m){maxLoan = m;}
    35. void ResetRate(double r){rate = r;}
    36. void ResetOwes(){owesBank = 0;}
    37. };
    38. #endif // BRASS_H

     

    1. #include
    2. #include "brass.h"
    3. typedef std::ios_base::fmtflags format;
    4. typedef streamsize precis;
    5. format setFormat();
    6. void restore(format f, precis p);
    7. Brass:: Brass(const string& s, long an, double bal)
    8. {
    9. fullName = s;
    10. acctNum = an;
    11. balance = bal;
    12. }
    13. //存钱
    14. void Brass::Deposit(double amt)
    15. {
    16. if(amt < 0)
    17. cout << "negative deposit not allowed; " << "deposit is cancelled.\n";
    18. else
    19. balance += amt;
    20. }
    21. //取钱
    22. void Brass::Withdrow(double amt)
    23. {
    24. format initialState = setFormat();
    25. precis prec = cout.precision(2);
    26. if(amt < 0)
    27. cout << "negative withdrow not allowed; " << "withdrow is cancelled.\n";
    28. else if (amt <= balance)
    29. balance -= amt;
    30. else
    31. cout << "withdrawal amount of $" << amt << " exceeds your balance.\n";
    32. restore(initialState, prec);
    33. }
    34. //查询账户余额
    35. double Brass::Balance() const
    36. {
    37. return balance;
    38. }
    39. void Brass::ViewAcct() const
    40. {
    41. //format initialState = setFormat();
    42. //precis prec = cout.precision(2);
    43. cout << "Client: " << fullName << endl;
    44. cout << "Account Number: " << acctNum << endl;
    45. cout << "Balance: $" << balance << endl;
    46. //restore(initialState, prec);
    47. }
    48. BrassPlus::BrassPlus(const string& s, long an, double bal, double ml, double r):Brass(s, an, bal)
    49. {
    50. maxLoan = ml;
    51. owesBank = 0.0;
    52. rate = r;
    53. }
    54. BrassPlus::BrassPlus(const Brass& ba, double ml, double r):Brass(ba)
    55. {
    56. maxLoan = ml;
    57. owesBank = 0.0;
    58. rate = r;
    59. }
    60. void BrassPlus::ViewAcct() const
    61. {
    62. format initialState = setFormat();
    63. precis prec = cout.precision(2);
    64. Brass::ViewAcct();
    65. //cout << "maximumloan: " << maxLoan << endl;
    66. cout << "maximumloan: " << maxLoan << endl;
    67. cout << "owed to bank " << owesBank << endl;
    68. cout.precision(3);
    69. cout << "Loan Rate: " << 100 * rate << "%\n";
    70. restore(initialState, prec);
    71. }
    72. void BrassPlus::Withdrow(double amt)
    73. {
    74. format initialState = setFormat();
    75. precis prec = cout.precision(2);
    76. double bal = Balance();
    77. if(amt <= bal)
    78. Brass::Withdrow(amt);
    79. else if(amt <= bal + maxLoan - owesBank)
    80. {
    81. double advance = amt - bal;
    82. owesBank += advance * (1.0 + rate);
    83. cout << "Bank advance: $" << advance << endl;
    84. cout << "Finance change: $" << advance * rate << endl;
    85. Deposit(advance);
    86. Brass::Withdrow(amt);
    87. }
    88. else
    89. cout << "Credit limit exceeded. Transaction cancelled.\n";
    90. restore(initialState, prec);
    91. }
    92. format setFormat()
    93. {
    94. return cout.setf(ios_base::fixed, ios_base::floatfield);
    95. }
    96. void restore(format f, precis p)
    97. {
    98. cout.setf(f, ios_base::floatfield);
    99. cout.precision(p);
    100. }
    1. #include
    2. #include "brass.h"
    3. int main()
    4. {
    5. Brass Jiayin("Xu Jiayin", 381299, 4000.00);
    6. BrassPlus Nianyu("beiji Nianyu", 382288, 3000.00);
    7. Jiayin.ViewAcct();
    8. cout << endl;
    9. Nianyu.ViewAcct();
    10. cout << endl;
    11. cout << "Depositing $1000 into the Nianyu Account:\n";
    12. Nianyu.Deposit(1000.00);
    13. cout <<"new balance: $" << Nianyu.Balance() << endl;
    14. cout << "withdrawing $4200 from the Jiayin Account:\n";
    15. Jiayin.Withdrow(4200.00);
    16. cout <<"Jiayin account balance: $" << Jiayin.Balance() << endl;
    17. cout << "withdrawing $4200 from the Nianyu Account:\n";
    18. Nianyu.Withdrow(4200.00);
    19. Nianyu.ViewAcct();
    20. return 0;
    21. }

    静态联编与动态联编

    程序调用函数时,将使用哪个可执行块,是由编译器决定的。将源代码中的函数调用截石位执行特定的函数代码块的过程被称为函数名联编binding。在C语言中,这很简单,因为每个函数名都对应一个不同的函数。在C++中由于函数重载的缘故,这项任务更复杂。编译器必须查看函数参数和函数名才能确定使用哪个函数。但是编译器可以在编译过程中完成这种联编。在编译过程中进行联编就是静态联编。也叫早期联编。但是虚函数的存在,又加深了难度,在编译的时候是不知道该使用哪个函数的,所以编译器必须生成能够在程序运行时选择正确的虚方法的代码,这被称为动态联编,也叫晚期联编。

    有关虚函数的注意事项

    1、在基类的成员函数的声明中,使用关键字virtual,可使该函数在基类以及所有的派生类中都是虚的;

    2、如果使用指向对象的引用或指针来调用虚函数,程序将使用为对象类型定义的函数,而不是使用引用或指针定义的函数。这也称为动态联编;

    3、如果定义的类被作为基类,则应将那些要在派生类中重新定义的成员函数声明为虚函数。

    4、构造函数不能是虚函数;

    5、析构函数应当是虚函数;

  • 相关阅读:
    2.5 C#视觉程序开发实例1----CamManager实现模拟相机采集图片(Form_Vision部分代码)
    Spring Boot 2 (四):使用 Docker 部署 Spring Boot
    阿里云操作日记
    Python学习笔记第六十八天(Matplotlib 饼图)
    鸿蒙APP外包开发上线流程
    200PLC转以太网与研华webaccess modbusTCP客户端在空调机上应用配置案例
    一键式 new 多个相同的实例(通过界面按钮 来控制 应用的创建、修改、删除,使用Docker Compose 编排应用所需环境)
    【Java基础 | IO流】File类概述和常用方法使用
    计算机毕业设计ssm儿童福利院管理系统5d7wb系统+程序+源码+lw+远程部署
    【ZLM】花屏现象记录
  • 原文地址:https://blog.csdn.net/m0_49968063/article/details/133994572