继承与派生

什么是继承和派生

在这里插入图片描述

父亲“派生”出儿子
儿子“继承”自父亲
派生和派生,本质是相同的,只是从不同的角度来描述。

继承和派生在UML中的表示

注意是“空心三角箭头”,从子类【派生的类】指向父类【被继承的类】
父类,也称为“基类”

除了“构造函数”和“析构函数”,
父类的所有成员函数,以及数据成员,都会被子类继承!

在这里插入图片描述

派生和继承的实现

在这里插入图片描述
Father.h

#pragma once
#include <string>

using namespace std;

class Father
{
public:
	Father(const char*name, int age);
	~Father();

	string getName();
	int getAge();
	string description();

private:
	int age;
	string name;
};

Father.cpp

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


Father::Father(const char*name, int age)
{
	cout << __FUNCTION__ << endl;
	this->name = name;
	this->age = age;
}


Father::~Father()
{
}

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

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

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

Son.h

#pragma once
#include "Father.h"

class Son : public Father {
public:
	Son(const char *name, int age, const char *game);
	~Son();
	string getGame();
	string description();
private:
	string game;
};

Son.cpp

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

// 创建Son对象时, 会调用构造函数!
// 会先调用父类的构造函数, 用来初始化从父类继承的数据 
// 再调用自己的构造函数, 用来初始化自己定义的数据
Son::Son(const char *name, int age, const char *game) : Father(name, age) {
	cout << __FUNCTION__ << endl;

	// 没有体现父类的构造函数, 那就会自动调用父类的默认构造函数!!!
	this->game = game;
}

Son::~Son() {

}

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

string Son::description() {
	stringstream ret;

	// 子类的成员函数中, 不能访问从父类继承的private成员
	ret << "name:" << getName() << " age:" << getAge()
		<< " game:" << game;
	return ret.str();
}

main.cpp

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

int main(void) {
	Father wjl("王健林", 68);
	Son wsc("王思聪", 32, "电竞");

	cout << wjl.description() << endl;

	// 子类对象调用方法时, 先在自己定义的方法中去寻找, 如果有, 就调用自己定义的方法
	// 如果找不到, 就到父类的方法中去找, 如果有, 就调用父类的这个同名方法
	// 如果还是找不到, 就是发生错误!
	cout << wsc.description() << endl;
	
	system("pause");
	return 0;
}

派生类(子类)对象的内存分布

在这里插入图片描述
在这里插入图片描述
说明:成员函数,不占用对象的内存空间,但是也被子类继承了!!!

  • 10
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Respect@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值