C++浅谈(三):类的继承

在people.h和people.cpp中做如下修改方便以后的使用:

#include <iostream>
class people
{
private:       //私有成员变量
	int age;
	int sex;
public:         // 公有
	people();//默认构造方法
	people(int age,int sex); //构造方法
	int getAge();
	int getSex();
	void sayhello();
};
# include<iostream>
#include "people.h"
using namespace std;

people::people(){ //默认的构造方法,不指定执行父类的构造方法,则执行默认的
	this->age = 10;
	this->sex = 1;
}

people::people(int age,int sex){  //实现构造方法
	this->age = age;
	this->sex = sex;
}

int people::getAge()
{
	return this->age;
}

int people::getSex(){
	return this->sex;
}
void people::sayhello()
{
	cout << "Hello World\n";
}

然后再创建一个Man类继承people类

Man.h如下:

#pragma once
#include "C:\Users\dell\Documents\Visual Studio 2013\Projects\01\01\people.h"
class Man :
	public people    //“:”表示继承
{
public:

};

Man.cpp如下调用Man.h实现people中的方法:

# include<iostream>
# include"Man.h"
int main(int argc, const char * argv[])
{
	Man *m= new Man();
	m->sayhello();             //通过指针p访问到成员方法
	delete m;   //释放内存空间
	system("pause");
	return 0;
}
运行后,输出结果如上次^_^。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值