C++中继承的基本概念

1 C++中继承的基本概念

1.1 继承的基本概念

继承关系就是父子关系,UML图如下:
在这里插入图片描述
注意是“空心三角箭头”,从子类【派生的类】指向父类【被继承的类】。父类,也称为“基类”。

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

面向对象中的继承指类之间的父子关系:

  • 子类拥有父类的所有属性和行为。
  • 子类就是一种特殊的父类(子类对象可以直接初始化父类对象,子类对象可以直接赋值给父类对象)。
  • 子类对象可以当作父类对象使用。
  • 子类中可以添加父类没有的方法和属性。

C++中通过下面的方式描述继承关系:
在这里插入图片描述
继承示例代码:

#include <iostream>
#include <string>

using namespace std;

class Parent
{
    int mv;
public:
    Parent()
    {
        cout << "Parent()" << endl;
        mv = 100;
    }
    void method()
    {
        cout << "mv = " << mv << endl;
    }
};

class Child : public Parent
{
public:
    void hello()
    {
        cout << "I'm Child calss!" << endl;
    }
};

int main()
{   
    Child c;
    
    c.hello();
    c.method();
    
    return 0;
}

1.2 继承的意义

继承是C++中代码复用的重要手段。通过继承,可以获得父类的所有功能,并且可以在子类中重写已有功能,或者添加新功能。

1.3 继承实例分析

继承图如下:
在这里插入图片描述

代码如下:
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;
}

子类, 一般会添加自己的数据成员/成员函数, 或者, 重新定义从父类继承的方法!!! 子类对象就会调用自己重新定义的方法, 不会调用父类的同名方法。


参考资料:

  1. C++深度解析教程
  2. C/C++从入门到精通-高级程序员之路【奇牛学院】
发布了271 篇原创文章 · 获赞 28 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/SlowIsFastLemon/article/details/104252269