继承
Day7-2 继承-基类和派生类
一、继承
1、继承的基础
面向对象的四大基本特征:抽象、封装、继承、多态。
- 继承:从既有类(基类)产生新类(派生类)的过程。
- 基类(父类):已有的类。
- 派生类(子类):从基类继承并扩展的新类。
2、继承的定义
class 子类(派生类)
: public/protected/private 父类(基类) //类派生列表
{
//数据成员
//成员函数
};
3. 派生类的构造过程
- 吸收 基类的成员。
- 改造 基类的成员。
- 新增 自己的成员。
示例代码:
#include <iostream>
using namespace std;
class Base {
public:
Base() : _base(0) {
cout << "Base()" << endl; }
~Base() {
cout << "~Base()" << endl; }
private:
long _base;
};
class Derived : public Base {
public:
//如果派生类显式定义了构造函数,而基类没有显式定义构造函数
//则创建派生类的对象时,派生类相对应的构造函数会被自动调用,
//此时都自动调用了基类缺省的构造函数
Derived(long derived = 0) : _derived(derived) {
cout << "Derived()" << endl; }
~Derived() {
cout << "~Derived()" << endl; }
private:
long _derived;
};
int main()
{
//在创建派生类对象的时候,会先调用基类的构造函数,然后调用派生类的构造函数 ??-->
//上面的说法是典型的错误,正确的如下:
//在创建派生类对象的时候,会调用派生类自己的构造函数,但是为了完成从基类吸收过来的数据成员的初始化,所以才会调用基类的构造函数
Derived d1(10);
cout << "When creating a derived class object, the derived class's own constructor is called, "
<<"but in order to complete the initialization of the data members absorbed from the base class,"
<<" the base class's constructor is called" << endl;
return 0;
}
派生类对象的构造顺序:
- 先调用基类的构造函数。
- 然后调用派生类的构造函数。
4、继承的局限
以下内容不会被继承:
- 基类的构造函数和析构函数
- 基类的友元关系
- 基类的
operator new/delete
操作符
#include <string>
#include <iostream>
/*
从 Circle 中提取一些公有的成员到基类 Shape 中
*/
class Shape
{
private: // 如须让子类可见,应使用 protected
double _x;
double _y;
std::string _name;
public:
Shape() : Shape(0.0, 0.0) {
}
Shape(double x, double y, const std::string& name = "")
: _x(x), _y(y), _name(name) {
}
Shape(const std::string& name) : Shape(0.0, 0.0, name) {
}
~Shape() = default;
double x() const {
return _x; }
double y() const {
return _y; }
const std::string& name() const {
return _name; }
void setX(