zoukankan      html  css  js  c++  java
  • [C++]C++学习笔记(五)

    1,类继承 公有继承:基类的公有成员将成为派生类的公有成员,基类的私有成员也将成为派生类的一部分,但是只能通过派生类的公有方法和保护方法访问 具体示例如下: 基类:

    1. #ifndef TABTENN0_H_  
    2. #define TABTENN0_H_  
    3. #include <string>  
    4. using std::string;  
    5. // simple base class  
    6. class TableTennisPlayer  
    7. {  
    8. private:  
    9.     string firstname;  
    10.     string lastname;  
    11.     bool hasTable;  
    12. public:  
    13.     TableTennisPlayer (const string & fn = "none",  
    14.                        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. #endif  
    20. #include "tabtenn0.h"  
    21. #include <iostream>  
    22.   
    23. TableTennisPlayer::TableTennisPlayer (const string & fn,   
    24.     const string & ln, bool ht) : firstname(fn),  
    25.         lastname(ln), hasTable(ht) {}  
    26.       
    27. void TableTennisPlayer::Name() const  
    28. {  
    29.     std::cout << lastname << ", " << firstname;  
    30. }  

    派生类

    1. class RatedPlayer : public TableTennisPlayer  
    2. {  
    3. private:  
    4.     unsigned int rating;  
    5. public:  
    6.     RatedPlayer (unsigned int r = 0, const string & fn = "none",  
    7.                  const string & ln = "none", bool ht = false);  
    8.     RatedPlayer(unsigned int r, const TableTennisPlayer & tp);  
    9.     unsigned int Rating() const { return rating; }  
    10.     void ResetRating (unsigned int r) {rating = r;}  
    11. };  
    12. RatedPlayer::RatedPlayer(unsigned int r, const string & fn,  
    13.      const string & ln, bool ht) : TableTennisPlayer(fn, ln, ht)  
    14. {  
    15.     rating = r;  
    16. }  
    17.   
    18. RatedPlayer::RatedPlayer(unsigned int r, const TableTennisPlayer & tp)  
    19.     : TableTennisPlayer(tp), rating(r)  
    20. {  
    21. }  

    派生类构造函数: 派生类不能直接访问基类的私有成员,必须通过基类的方法访问:创建派生类对象之前,程序首先创建基类对象。 派生类可以使用基类的方法,条件是方法不是私有的。 基累的指针可以在不进行显式类型转换的情况下指向派生类对象,基类引用可以在不进行显式转换情况下引用派生类对象 然而基类引用或者指针只能调用基类的方法 RatedPlayer rpplayer(1140,"Mall","Duck",true); TableTennisPlayer &rt=rpplayer; TableTennisPlayer *rt=&rpplayer;

    2,多态公有继承 多态继承的含义是派生类继承基类的方法,但是基类的某些方法派生类希望修改。 两种机制可以满足,在派生类中重新定义基类的方法,使用虚方法 具体方法是在基类和派生类中声明方法的时候都在前面加上 virtual 关键字 虚函数原理: 每个类都包含一个指向本类的虚函数地址数组的指针,即虚函数表 虚函数注意事项: 如果使用指向对象的引用或指针来调用虚函数,程序则使用对象类型定义的方法。 构造函数不能是虚函数 析构函数应该是虚函数 友元不能是虚函数

    3,类的保护乘员  protected关键字 对外部世界来说,保护成员和私有成员类似,但是对派生类来说,保护乘员和公有成员一样

  • 相关阅读:
    Linux下中文乱码
    hive配置元数据库mysql文件配置
    centos7安装mysql5.6
    mapreduce案例:获取PI的值
    hadoop第一个程序WordCount
    centos7搭建伪分布式集群
    Centos7永久关闭防火墙
    centos7设置静态ip
    大数据技术之kettle
    2020/6/20 mysql表连接和子查询
  • 原文地址:https://www.cnblogs.com/zhiliao112/p/4069206.html
Copyright © 2011-2022 走看看