c++类和对象-继承
参考链接:46 类和对象-继承-继承方式_哔哩哔哩_bilibili
1.概述
作用:提高代码复用率,多个子类和父类有相同之处,又有自己各自的特点。例如基类人有四肢、会走路、说话,不同子类中国人是黑头发,说汉语,欧洲人黄头发,说英语。
2.子类继承属性访问权限
子类会继承父类所有非静态成员属性(包括方法和变量)
继承方式:public、protected、private
子类无法访问父类private权限内容(内存模型中其实也被继承了,被编译器隐藏了)
public成员 | protected成员 | private成员 | |
public继承 | public访问权限 | protected访问权限 | 不可访问 |
protected继承 | protected访问权限 | protected访问权限 | 不可访问 |
private继承 | private访问权限 | private访问权限 | 不可访问 |
3.构造和析构顺序
先调用父类构造函数,再调用子类构造函数
先调用子类析构函数,再调用父类析构函数
3.1问题
1.子类构造和父类构造函数传参不同,如何激活父类构造函数?
会默认调用父类的默认构造函数,父类不存在默认构造函数需要手动指定调用那个父类构造函数。
#include <iostream>using namespace std; class Parent {
public:/*Parent() {cout << "Parent constructor called" << endl;}*/Parent(int age) {this->age = age; // 初始化父类成员变量cout << "Parent constructor with age called, age: " << age << endl;}~Parent() {cout << "Parent destructor called" << endl;}int age = 0; // 父类成员变量
};class Child : public Parent {
public://父类没有默认构造函数,需要手动调用父类构造函数Child() : Parent(20){cout << "Child constructor called" << endl;}Child(int age) : Parent(age + 20){this->age = age; // 初始化父类成员变量cout << "Child constructor with age called, age: " << age << endl;}~Child() {cout << "Child destructor called" << endl;}};void test() {Child child(10); // 创建 Child 对象时会调用 Parent 的构造函数
}int main() {test();return 0;
}
输出
4.继承中同名成员处理
1.子类同名变量会直接覆盖父类变量
2.同名成员函数会隐藏父类所有该名字的函数(不会触发重载)
3.通过添加父类作用域可以访问父类同名被隐藏的变量和方法
其他
1.子类对象大小为子类所有非静态成员变量大小(包括所有继承自父类的成员变量)