组合与继承:
组合:has-a关系
继承:is-a关系
C++类的继承,指用现有类来创建新的类,即新类会获得已有类的属性和行为,并且可以添加新的属性和
行为
新的类称为子类或派生类,已有类称为父类或基类!
格式:
class 派生类名: 继承方式 基类名
{
//派生类新增加的成员
};
继承的过程:
1.接收基类的成员
2.修改成员的访问权限或隐藏基类中不需要的东西
3.添加新的属性和行为
继承方式:
public:公有继承
priavte:私有继承
protected:保护继承
继承方式决定了 基类中的成员 在派生类内部和在派生类的外部 的访问权限。
公有继承:(掌握)
基类的公有成员、保护成员会成为派生类的公有成员和保护成员,基类的私有成员成为派生类的不可访问成员
私有继承:(了解)
基类的公有成员、保护成员会成为派生类的私有成员,基类的私有成员成为派生类的不可访问成员
保护继承:(了解)
基类的公有成员、保护成员会成为派生类的保护成员,基类的私有成员成为派生类的不可访问成员
-------------------------------------------------------------------------------------------------
#include<iostream> using namespace std; class Student { public: void study() { cout << "学习使我快乐!\n"; } }; class xStudent:public Student { public: void study() { cout << "小学生学习四则运算!\n"; } }; class zStudent:public Student { public: void study(int a) { cout << "中学生学学习几何代数!\n"; } }; int main() { xStudent x; x.study(); x.Student::study(); zStudent z; z.study(10); z.Student::study(); return 0; }
继承中的构造函数与析构函数:
构造函数与析构函数不能被继承
特性:
1.如果基类和派生类有默认的构造函数,编译器会自动调用
2.如果需要把参数传递给基类的构造函数,必须定义带参数的构造函数,且需要以派生类的初始化表的形式调用基类的构造函数
3.在调用派生类的构造函数之前,会先调用基类的构造函数。
4.在派生类对象被销毁时,会先调用派生类自己的析构函数,再调用基类的析构函数
-------------------------------------------------------------------------------------------------
#include<iostream> using namespace std; class Parent { public: Parent() { a = 10; } Parent(int a):a(a) { cout << "Parent(int)" << endl; } void show() { cout << "a = " << a << endl; } ~Parent() { cout << "~Parent()" << endl; } private: int a; }; class Child:public Parent { public: Child() { b = 10; } Child(int a,int b):b(b),Parent(a) { cout << "Child(int,int)" << endl; } void show() { // cout << "a = " << a << endl; Parent::show(); cout << "b = " << b << endl; } ~Child() { cout << "~Child() " << endl; } private: int b; }; int main() { Child c(100,200); c.show(); return 0; }