继承的概念及定义
继承的概念
继承机制是⾯向对象程序设计使代码可以复用的最重要的手段,它允许我们在保持原有类特性的基础上进行扩展,增加方法(成员函数)和属性(成员变量),这样产生新的类,称派生类。继承呈现了面向对象程序设计的层次结构,体现了由简单到复杂的认知过程。以前我们接触的函数层次的复用,继承是类设计层次的复用。
下面有两个类Student和Teacher,Student和Teacher都有姓名/地址/电话/年龄等成员变量,都有identity⾝份认证的成员函数,设计到两个类里面就是冗余的。当然他们也有⼀些不同的成员变量和函数,比如老师独有成员变量是职称,学生的独有成员变量是学号;学生的独有成员函数是学习,老师的独有成员函数是授课。
#include<iostream>
using namespace std;
class Student
{
public:
// 进⼊校园/图书馆/实验室刷⼆维码等⾝份认证
void identity()
{
// ...
}
// 学习
void study()
{
// ...
}
protected:
string _name = "peter"; // 姓名
string _address; // 地址
string _tel; // 电话
int _age = 18; // 年龄
int _stuid; // 学号
};
class Teacher
{
public:
// 进⼊校园/图书馆/实验室刷⼆维码等⾝份认证
void identity()
{
// ...
}
// 授课
void teaching()
{
//...
}
protected:
string _name = "张三"; // 姓名
int _age = 18; // 年龄
string _address; // 地址
string _tel; // 电话
string _title; // 职称
};
int main()
{
return 0;
}
下面把公共的成员都放到Person类中,Student和Teacher都继承Person,就可以复用这些成员,就不需要重复定义了,省去了很多麻烦。
class Person
{
public:
void identity()
{
cout << "void identity()" << _name << endl;
}
protected:
string _name = "张三"; //姓名
int _age; //年龄
string _address = "浙江省"; //地址
string _tel; // 电话
};
class Studemt : public Person
{
public:
void study()
{}
protected:
int _stuid;
};
class Teacher : public Person
{
public:
void teaching()
{}
protected:
string _title;
};
int main()
{
return 0;
}
继承定义
定义格式
Person是基类,也称作父类。Student是派生类,也称作子类。(因为翻译的原因,所以既叫基类/派生类,也叫父类/子类)
继承基类成员访问方式的变化
类成员/继承方式 | public继承 | protected继承 | private继承 |
---|---|---|---|
基类的public成员 | 派生类的public成员 | 派生类的protected成员 | 派生类的private成员 |
基类的protected成员 | 派生类的protected成员 | 派生类的protected成员 | 派生类的private成员 |
基类的private成员 | 在派生类中不可见 | 在派生类中不可见 | 在派生类中不可见右 |
- 基类private成员在派生类中无论以什么方式继承都是不可见的。这⾥的不可见是指基类的私有成员还是被继承到了派生类对象中,但是语法上限制生类对象不管在类里面还是类外面都不能去访问它。
- 基类private成员在派生类中是不能被访问,如果基类成员不想在类外直接被访问,但需要在派生类中能访问,就定义为protected。可以看出保护成员限定符是因继承才出现的。
- 实际上面的表格进行⼀下总结会发现,基类的私有成员在派生类都是不可见。基类的其他成员在派生类的访问方式==Min(成员在基类的访问限定符,继承方式),public >protected>private。
- 使用关键字class时默认的继承方式是private,使用struct时默认的继承方式是public,不过最好显示的写出继承方式。
- 在实际运用中⼀般使用都是public继承,几乎很少使用protetced/private继承,也不提倡使用protetced/private继承,因为protetced/private继承下来的成员都只能在派生类的类里面使用,实际中扩展维护性不强。
class Person
{
public:
void Print()
{
cout << _name << endl;
}
protected:
string _name;
private:
int _age;
};
class Student : private Person
{
protected:
string _stunum;
};
int main()
{
Student s;
s.Print();
return 0;
}
继承类模板
namespace my
{
template<class T>
class stack : public std::vector<T>
{
public:
void push(const T& x)
{
// 基类是类模板时,需要指定⼀下类域,
// 否则编译报错:error C3861: “push_back”: 找不到标识符
// 因为stack<int>实例化时,也实例化vector<int>了
// 但是模版是按需实例化,push_back等成员函数未实例化,所以找不到
std::vector<T>::push_back(x);
}
void pop()
{
std::vector<T>::pop_back();
}
const T& top()
{
return std::vector<T>::back();
}
bool empty()
{
return std::vector<T>::empty();
}
};
}
int main()
{
my::stack<int> st;
st.push(1);
st.push(2);
st.push(3);
st.push(1);
while (!st.empty())
{
cout << st.top() << " ";
st.pop();
}
return 0;
}
基类和派生类间的转换
- public继承的派生类对象可以赋值给基类的指针/基类的引用。这⾥有个形象的说法叫切片或者切割。寓意把派生类中基类那部分切出来,基类指针或引⽤指向的是派生类中切出来的基类那部分。
- 基类对象不能赋值给派生类对象。
- 基类的指针或者引用可以通过强制类型转换赋值给派生类的指针或者引用。但是必须是基类的指针是指向派生类对象时才是安全的。这里基类如果是多态类型,可以使用RTTI(Run-Time Type Information)的dynamic_cast来进行识别后进行安全转换。
class Person
{
protected:
string _name;
string _sex;
int _age;
};
class Student : public Person
{
public:
int _no;
};
int main()
{
Student sobj;
// 派生类对象可以直接赋值给基类,是通过调用基类的拷贝构造完成的
Person pobj = sobj;
// 派生类对象可以赋值给基类的指针/引⽤
Person* pp = &sobj;
Person& rp = sobj;
//基类对象不能赋值给派生类对象,这⾥会编译报错
sobj = pobj;
return 0;
}
继承中的作用域
隐藏规则
- 在继承体系中基类和派生类都有独立的作用域。
- 派生类和基类中有同名成员,派生类成员将屏蔽基类对同名成员的直接访问,这种情况叫隐藏。(在派生类成员函数中,可以使用基类::基类成员 显示访问)
- 需要注意的是如果是成员函数的隐藏,只需要函数名相同就构成隐藏。
- 注意在实际中在继承体系里面最好不要定义同名的成员。
class Person
{
protected:
string _name = "张三";
int _num = 111;
};
class Student : public Person
{
public:
void Print()
{
cout << "姓名" << _name << endl;
//cout << "编号" << Person::_num << endl;
cout << "学号" << _num << endl;
}
protected:
int _num = 999;
};
int main()
{
Student s1;
s1.Print();
return 0;
}
考察继承作用域相关选择题
class A
{
public:
void fun()
{
cout << "func()" << endl;
}
};
class B : public A
{
public:
void fun(int i)
{
cout << "func(int i)" << i << endl;
}
};
int main()
{
B b;
b.fun(10);
b.fun();
return 0;
};
- A和B类中的两个func构成什么关系()
A. 重载 B. 隐藏 C. 没关系 - 下面程序的编译运行结果是什么()
A. 编译报错 B. 运行报错 C.正常运行
第一题的答案为A,因为A和B类的函数名都为fun,成员函数的隐藏,只需要函数名相同就构成隐藏
第二题的答案为A,错误出现在b.fun()中,若想调用A类中的fun()函数,需要b.A::fun();这么写
派生类的默认成员函数
4个常见默认成员函数
6个默认成员函数,默认的意思就是指我们不写,编译器会变我们自动生成⼀个,那么在派生类中,这几个成员函数是如何生成的呢?
- 派生类的构造函数必须调用基类的构造函数初始化基类的那⼀部分成员。如果基类没有默认的构造函数,则必须在派生类构造函数的初始化列表阶段显示调用。
- 派生类的拷贝构造函数必须调用基类的拷贝构造完成基类的拷贝初始化。
- 派生类的operator=必须要调用基类的operator=完成基类的复制。需要注意的是派生类的operator=隐藏了基类的operator=,所以显示调用基类的operator=,需要指定基类作用域。
- 派生类的析构函数会在被调用完成后自动调用基类的析构函数清理基类成员。因为这样才能保证派生类对象先清理派生类成员再清理基类成员的顺序。
- 派生类对象初始化先调用基类构造再调派生类构造。
- 派生类对象析构清理先调用派生类析构再调基类的析构。
- 因为多态中⼀些场景析构函数需要构成重写,重写的条件之⼀是函数名相同。那么编译器会对析构函数名进行特殊处理,处理成destructor(),所以基类析构函数不加virtual的情况下,派生类析构函数和基类析构函数构成隐藏关系。
class Person
{
public:
Person(const char* name = "张三")
: _name(name)
{
cout << "Person()" << endl;
}
Person(const Person& p)
: _name(p._name)
{
cout << "Person(const Person& p)" << endl;
}
Person& operator=(const Person& p)
{
cout << "Person& operator=(const Person& p)" << endl;
if (this != &p)
{
_name = p._name;
}
return* this;
}
~Person()
{
cout << "~Person()" << endl;
}
protected:
string _name;
};
class Student : public Person
{
public:
Student(const char* name, int num)
:Person(name)
, _num(num)
{
cout << "Student()" << endl;
}
Student(const Student& s)
:Person(s)
, _num(s._num)
{
cout << "Student(const Student& s)" << endl;
}
Student& operator=(const Student& s)
{
cout << "Student& operator=(const Student& s)" << endl;
if (this != &s)
{
Person::operator=(s);
_num = s._num;
}
return *this;
}
~Student()
{
cout << "~Student()" << endl;
}
protected:
int _num;
};
int main()
{
Student s1("jack", 18);
Student s2(s1);
Student s3("rose", 17);
s1 = s3;
return 0;
}
可以看出不管是构造,拷贝构造,赋值,都是先调用基类,再调用派生类;在析构时,派生类对象先析构派生类成员再析构基类成员
实现一个不能被继承的类
- 基类的构造函数私有,派生类的构成必须调用基类的构造函数,但是基类的构成函数私有化以后,派生类看不见就不能调用了,那么派生类就无法实例化出对象。
- C++11新增了⼀个
final
关键字,final
修改基类,派生类就不能继承了。
class Base
{
public:
void fun5()
{
cout << "Base::fun5()" << endl;
}
protected:
int a = 1;
private:
Base()
{
}
};
class Derive : public Base
{
public:
void fun4()
{
cout << "Derive::fun4()" << endl;
}
protected:
int b = 2;
};
int main()
{
Base b;
Derive d;
return 0;
}
class Base final
{
public:
void fun5()
{
cout << "Base::fun5()" << endl;
}
protected:
int a = 1;
};
class Derive : public Base
{
public:
void fun4()
{
cout << "Derive::fun4()" << endl;
}
protected:
int b = 2;
};
int main()
{
Base b;
Derive d;
return 0;
}
继承与友元
友元关系不能继承,也就是说基类友元不能访问派生类私有和保护成员
class Student;
class Person
{
public:
friend void Display(const Person& p, const Student& s);
protected:
string _name;
};
class Student : public Person
{
protected:
int _stunum;
};
void Display(const Person& p, const Student& s)
{
cout << p._name << endl;
cout << s._stunum << endl;
}
int main()
{
Person p;
Student s;
return 0;
}
可以看到派生类无法继承基类的友元,需要在派生类中也写上友元
class Student;
class Person
{
public:
friend void Display(const Person& p, const Student& s);
protected:
string _name;
};
class Student : public Person
{
public:
friend void Display(const Person& p, const Student& s);
protected:
int _stunum;
};
void Display(const Person& p, const Student& s)
{
cout << p._name << endl;
cout << s._stunum << endl;
}
int main()
{
Person p;
Student s;
return 0;
}
继承与静态成员
基类定义了static
静态成员,则整个继承体系里面只有⼀个这样的成员。无论派生出多少个派生类,都只有⼀个static
成员实例。
class Person
{
public:
string _name;
static int _count;
};
int Person::_count = 1;
class Student : public Person
{
protected:
int _stuNum;
};
int main()
{
Person p;
Student s;
// 这⾥的运行结果可以看到非静态成员_name的地址是不⼀样的
// 说明派生类继承下来了,父、派生类对象各有⼀份
cout << &p._name << endl;
cout << &s._name << endl;
// 这里的运行结果可以看到静态成员_count的地址是⼀样的
// 说明派生类和基类共用同⼀份静态成员
cout << &p._count << endl;
cout << &s._count << endl;
// 公有的情况下,父、派生类指定类域都可以访问静态成员
cout << Person::_count << endl;
cout << Student::_count << endl;
return 0;
}
多继承及其菱形继承问题
继承模型
- 单继承:⼀个派生类只有⼀个直接基类时称这个继承关系为单继承
- 多继承:⼀个派生类有两个或以上直接基类时称这个继承关系为多继承,多继承对象在内存中的模型是,先继承的基类在前面,后面继承的基类在后面,派生类成员在放到最后面。
- 菱形继承:菱形继承是多继承的⼀种特殊情况。菱形继承的问题,从下面的对象成员模型构造,可以看出菱形继承有数据冗余和⼆义性的问题,在Assistant的对象中Person成员会有两份。⽀持多继承就⼀定会有菱形继承,像Java就直接不支持多继承,规避掉了这里的问题,所以实践中也是不建议设计出菱形继承这样的模型的。
单继承
多继承
菱形继承
class Person
{
public:
string _name;
};
class Student : public Person
{
protected:
int _num;
};
class Teacher : public Person
{
protected:
int _id;
};
class Assistant : public Student, public Teacher
{
protected:
string _majorCourse;
};
int main()
{
Assistant a;
a._name = "张三";
return 0;
}
需要显示指定访问哪个基类的成员可以解决⼆义性问题,但是数据冗余问题无法解决
class Person
{
public:
string _name;
};
class Student : public Person
{
protected:
int _num;
};
class Teacher : public Person
{
protected:
int _id;
};
class Assistant : public Student, public Teacher
{
protected:
string _majorCourse;
};
int main()
{
Assistant a;
a.Student::_name = "XXX";
a.Teacher::_name = "YYY";
return 0;
}
虚继承
class Person
{
public:
string _name;
};
class Student : virtual public Person
{
protected:
int _num;
};
class Teacher : virtual public Person
{
protected:
int _id;
};
class Assistant : public Student, public Teacher
{
protected:
string _marjorcourse;
};
int main()
{
Assistant a;
a._name = "张三";
return 0;
}
使用虚继承,可以解决数据冗余和⼆义性
多继承中指针偏移问题?下面说法正确的是( )
A. p1 == p2 == p3
B. p1 < p2 < p3
C.p1 == p3 != p2
D. p1 != p2 !=p3
class Base1
{
public:
int _b1;
};
class Base2
{
public:
int _b2;
};
class Derive : public Base1, public Base2
{
public:
int _d;
};
int main()
{
Derive d;
Base1* p1 = &d;
Base2* p2 = &d;
Derive* p3 = &d;
return 0;
}
继承和组合
- public继承是⼀种is-a的关系。也就是说每个派生类对象都是⼀个基类对象。
- 组合是⼀种has-a的关系。假设B组合了A,每个B对象中都有⼀个A对象。
- 继承允许你根据基类的实现来定义派生类的实现。这种通过生成派生类的复用通常被称为白箱复用(white-box reuse)。术语“白箱”是相对可视性而言:在继承方式中,基类的内部细节对派生类可见。继承⼀定程度破坏了基类的封装,基类的改变,对派生类有很大的影响。派生类和基类间的依赖关系很强,耦合度高。
- 对象组合是类继承之外的另⼀种复用选择。新的更复杂的功能可以通过组装或组合对象来获得。对象组合要求被组合的对象具有良好定义的接口。这种复用风格被称为黑箱复用(black-box reuse),因为对象的内部细节是不可见的。对象只以“黑箱”的形式出现。组合类之间没有很强的依赖关系,耦合度低。优先使用对象组合有助于你保持每个类被封装。
- 优先使用组合,而不是继承。实际尽量多去用组合,组合的耦合度低,代码维护性好。不过也不太那么绝对,类之间的关系就适合继承(is-a)那就用继承,另外要实现多态,也必须要继承。类之间的关系既适合用继承(is-a)也适合组合(has-a),就用组合。
// Tire和Car更符合has-a的关系
class Tire
{
protected:
string _brand = "Michelin"; // 品牌
size_t _size = 17; // 尺⼨
};
class Car
{
protected:
string _colour = "⽩⾊"; // 颜⾊
string _num = "陕ABIT00"; // ⻋牌号
Tire _t1; // 轮胎
Tire _t2; // 轮胎
Tire _t3; // 轮胎
Tire _t4; // 轮胎
};
class BMW : public Car
{
public:
void Drive()
{
cout << "好开-操控" << endl;
}
};
// Car和BMW/Benz更符合is-a的关系
class Benz : public Car
{
public:
void Drive()
{
cout << "好坐-舒适" << endl;
}
};
template<class T>
class vector
{};
// stack和vector的关系,既符合is-a,也符合has-a
template<class T>
class stack : public vector<T>
{};
template<class T>
class stack
{
public:
vector<T> _v;
};
int main()
{
return 0;
}