C/C++:C++类的继承

一步一步往上爬:


类的继承。

首先建立第一个类People。

1)People.h。

#ifndef PEOPLE_H
#define PEOPLE_H

#include<iostream>

using namespace std;

class People
{
    public:                   //共有成员
        People();            //People的默认的构造方法
        void get_date();      //输入数据
        void get_age();      //用来获取age
        void get_sex();     //用来获取sex
        void say_hello();
    private:                  //私有成员
        int age;
        int sex;           //我们约定1为男,0为女。
};

#endif // PEOPLE_H

2)People.cpp

#include "People.h"

People::People(){
    this->age = 18;
    this->sex = 1;
}//当我们不用那个构造方法时,
 //我用的就是这个默认的构造方法。

void People::get_date(){
    cin >> this->age;
    cin >> this->sex;
}

void People::get_age(){
   cout << this->age << endl;
}

void People::get_sex(){
    cout << this->sex << endl;
}

void People::say_hello(){
    cout << "hello world !" << endl;
}



建立第二个类tt用以继承第一个类


1)tt.h。


<span style="font-size:18px;">
#ifndef TT_H
#define TT_H

#include "People.h"

class tt:public People  //继承People类
{
    public:
};

#endif // TT_H
</span>


主程序。


<span style="font-size:18px;">
#include "tt.h"

int main()
{
    tt *p = new tt();
    p -> say_hello();
    p -> get_date();
    p -> get_age();
    p -> get_sex();
    delete p;
    return 0;
}
</span>

当我们不用get_date()时。既用了People的默认构造方法。


#include "tt.h"

int main()
{
    tt *p = new tt();
    p -> say_hello();
    //p -> get_date();
    p:People();
    p -> get_age();
    p -> get_sex();
    delete p;
    return 0;
}


感觉有点姿势不大对。。求大神们给具体讲讲类的继承吧。。

~~~~(>_<)~~~~ 


PS:滴水可穿石。





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值