26.C++类的继承与派生

/*
 单继承:
 如果只得到一个基类的遗传信息称为单继承;
 如果得到多个基类的遗传信息称为多继承。
 单继承是指从一个基类派生一个或多个派生类,
 单继承派生类的定义格式如下:
 class 派生类名:继承方式 基类名
 {
    派生类的新成员
 };
 继承方式:
 ——公有继承(public)
 ——私有继承(private)
 ——保护继承(protected)
 如果没有明确指明继承方式,系统默认为私有继承
 */

//派生类公有继承(public)例
#include <iostream>
#include <string.h>
class father //定义父类
{
public:
    father();//构造函数
    void SkiColor();
    void hairColor();
    void display();
protected:
    char name[20];
    char native[20];
private:
    int age;
    
};
father::father()
{
    strcpy(name, "li zong");
    strcpy(native, "BeiJing");
    age=56;
}
void father::SkiColor()
{
    std::cout<<"the skin color is yellow"<<std::endl;
}
void father::hairColor()
{
    std::cout<<"the skin color is black"<<std::endl;
}
void father::display()
{
    std::cout<<"name:"<<name<<",native:"<<native<<",age:"<<age<<std::endl;
}

class son:public father //定义子类
{
public:
    son();//构造函数
    void weight();
protected:
    char name[20];
private:
    int sonAge;
};
son::son()
{
    strcpy(name, "li yun");
    sonAge=20;
}

void son::weight()
{
    std::cout<<"weight: 75KG"<<std::endl;
}

int main(int argc, const char * argv[])
{
    father f1;
    f1.display();//name:li zong,native:BeiJing,age:56
    f1.SkiColor();
    f1.hairColor();
    
    
    son s1;
    s1.weight();//weight: 75KG
    s1.display();//name:li zong,native:BeiJing,age:56
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值