---- 整理自狄泰软件唐佐林老师课程
文章目录
1. 组合关系:整体与部分的关系
1.1 实例分析:组合关系的描述
#include <iostream>
#include <string>
using namespace std;
class Memory
{
public:
Memory() {
cout << "Memory()" << endl;
}
~Memory() {
cout << "~Memory()" << endl;
}
};
class Disk
{
public:
Disk() {
cout << "Disk()" << endl;
}
~Disk() {
cout << "~Disk()" << endl;
}
};
class CPU
{
public:
CPU() {
cout << "CPU()" << endl;
}
~CPU() {
cout << "~CPU()" << endl;
}
};
class MainBoard
{
public:
MainBoard() {
cout << "MainBoard()" << endl;
}
~MainBoard() {
cout << "~MainBoard()" << endl;
}
};
class Computer
{
Memory mMem;
Disk mDisk;
CPU mCPU;
MainBoard mMainBoard;
public:
Computer() {
cout << "Computer()" << endl;
}
void power() {
cout << "power()" << endl;
}
void reset() {
cout << "reset()" << endl;
}
~Computer() {
cout << "~Computer()" << endl;
}
};
int main()
{
Computer c;
return 0;
}
1.2 类之间的组合关系
- 组合关系的特点:
- 将其它类的对象作为当前类的成员使用
- 当前类的对象与成员对象的生命期相同
- 成员对象在用法上与普通对象完全一致
2. 继承关系
- 面向对象中的继承表示 类之间的 父子关系:
- 子类 拥有父类的 所有属性和行为
- 根据面向对象理论:子类拥有父类的一切属性和行为
==> 子类能够直接访问父类的私有成员 - 根据 C++:外界不能直接访问类的 private 成员
==> 子类不能直接访问父类的私有成员 - 是否矛盾?⇒ 下一篇博客《44 - 继承中的访问级别》
- 根据面向对象理论:子类拥有父类的一切属性和行为
- 子类就是 一种 特殊的父类
- 子类对象 可以 当作父类对象 使用
- 子类中 可以添加 父类没有的方法和属性
- 子类 拥有父类的 所有属性和行为
2.1 C++ 中描述继承关系的代码形式
2.2 编程实验:继承初体验
#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;
}
2.3 重要规则
- 子类就是 一个特殊的父类
- 子类对象可以 直接初始化 父类对象
- 子类对象可以 直接赋值 给父类对象
#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;
Parent p1 = c; // 子类对象可直接初始化父类对象
Parent p2;
c.hello();
c.method();
p2 = c; // 子类对象可直接赋值给父类对象
return 0;
}
2.4 继承的意义
- 继承是 C++ 中代码复用的重要手段
- 通过继承,可以 获得父类的所有功能,并且可以 在子类中 重写已有功能 或者 添加新功能
3. 小结
- 继承是面向对象中类之间的一种关系
- 子类拥有父类的所有属性和行为
- 子类对象可以作为父类对象使用
- 子类中可以添加父类没有的方法和属性
- 继承是面向对象中代码复用的重要手段