继承一之继承方式

学过的东西忘得太快,唯有写下来还能时不时翻翻,不至于过眼就忘。
这几天又把C++捡起来重新看过,整理一份详细的笔记。

在C++中继承是非常重要的属性之一:

继承方式有三种:公有继承(public)、私有继承(private)、保护继承(protected)

  1. 公有继承(public)
    公有继承的特点:基类(父类)的公有成员和保护成员作为派生类(子类)的成员时,它们都保持原有的状态,而基类的私有成员仍然是私有的,不能被这个派生类的子对象所访问。

  2. 保护继承(protected)
    保护继承的特点:基类(父类)的所有公有成员和保护成员都成为派生类(子类)的保护成员,并且只能被它的派生类成员函数或友元访问,基类的私有成员仍然是私有的,不能被派生类的子对象所访问。

  3. 私有继承(private)
    私有继承的特点:基类(父类)的公有成员和保护成员都作为派生类(子类)的私有成员,并且不能被这个派生类的子对象所访问。

    eg: 公有继承访问基类公有函数成员和保护数据成员,若访问私有数据成员则报错[Error] ‘char Person::m_cSex’ is private

//Person.h文件
#include<string>
using namespace std;

class Person   //基类
{
public:
    Person();
    void play();
protected:
    string m_strName;
private:
    char m_cSex;    
};

//Solider.h文件
#include "Person.h"

class Solider:public Person  //派生类
{
public:
    Solider();
    void work();
protected:
    int m_iAge;
private: 
    int m_iFamliy;
};
//person.cpp文件
#include<iostream>
#include "Person.h "
using namespace std;

Person::Person()
{
    m_strName="Marry";
    m_cSex = 'm';
}
void Person::play()
{
    cout<<"Person--play()"<<endl;
    cout<<m_strName<<endl;
}
//Solider.cpp文件
#include<iostream>
#include"Solider.h"
using namespace std;

Solider::Solider()
{   
}
void Solider::work()
{
    m_strName="Jim";
    m_iAge=20;
    cout<<m_iAge<<endl;
    cout<<m_strName<<endl;
    cout<<"Solider--Work()"<<endl; 
}
//main.cpp
#include <iostream>
#include "solider.h"
int main(void) 
{
    Solider solider;
    solider.work();
    solider.play(); 
    return 0;
}

保护继承可以访问基类公有函数成员和保护数据成员,不能访问私有数据成员。只需更改class Solider:protected Person 即可测试。
同理class Solider:private Person.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值