什么是继承和派生
父亲“派生”出儿子
儿子“继承”自父亲
派生和派生,本质是相同的,只是从不同的角度来描述。
继承和派生在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;
}
派生类(子类)对象的内存分布
说明:成员函数,不占用对象的内存空间,但是也被子类继承了!!!