C++面向对象编程之派生

注意:

1、子类的成员函数中,不能访问从父类继承的private成员。

2、子类、一般会添加自己的数据成员/成员函数,

或者重新定义从父类继承的方法!!!子类就会调用自己重新定义的方法,不会调用父类同名的方法。

main主函数

#include<iostream>
#include"Father.h"
#include"Son.h"

int main()
{
	Father father("大刚", 35);
	Son son("小刚", 12, "电脑");
	cout << father.description() << endl;
	cout << son.description() << endl;
	cout << son.getName() << "从事的职业是:" << son.getGame() << endl;
}

son头文件

#pragma once
#include "Father.h"
class Son :
	public Father
{
public:
	Son(const string &name, const int &age, const string &game);
	string getGame();
	string description();

private:
	string name;
	int age;
	string game;
};

son.cpp文件

#include "Son.h"
#include<sstream>
Son::Son(const string & name, const int & age, const string & game):Father(name,age)
{
	this->game = game;
}

string Son::getGame()
{
	return game;
}

string Son::description()
{
	stringstream ret;
	ret << "姓名:" << getName() << "  年龄:" << getAge() << "  职业:" << getGame();
	return ret.str();
}

Father头文件类

#pragma once
#include<string>
using namespace std;

class Father
{
public:
	Father(const string &name, const int &age);
	string getName()const;
	int getAge()const;
	string description()const;

private:
	string name;
	int age;
};

Father.cpp

#include "Father.h"
#include<sstream>

Father::Father(const string & name, const int & age)
{
	this->name = name;
	this->age = age;
}

string Father::getName()const
{
	return name;
}

int Father::getAge()const
{
	return age;
}

string Father::description() const
{
	stringstream ret;
	ret << "name:" << name << "age:" << age;
	return ret.str();
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值