10.2 继承与多态

文章目录

继承

继承的作用是代码复用。派生类自动获得基类的除私有成员外的一切。基类描述一般特性,派生类提供更丰富的属性和行为。在构造派生类时,其基类构造函数先被调用,然后是派生类构造函数。在析构时顺序刚好相反。

cpp 复制代码
// 基类 LinearList
class LinearList{
    int *buffer;
    int size;
public:
    LinearList(int num){
        size = (num>10)?num:10;
        buffer = new int[size];
    }
    ~LinearList(){
        delete []buffer;
    }
    bool insert(int x, int i);  // 线性表第i个元素后插入新元素,返回成功或失败
    bool remove(int &x, int i); // 删除线性表第i个元素,返回成功或失败
    int element(int i) const; // 返回线性表第i个元素, const表示不会修改调用它的对象的任何非静态成员数据
    int search(int x) const; // 查找值为x的元素并返回其序号
    int length() const; //返回线性表的长度
};
// 派生类 Queue
class Queue:private LinearList{  // 基类的公有和保护成员均变成派生类的私有成员
public:
    bool enQueue(int x){  // 元素x入队,返回操作成功或失败
        return insert(x, length());
    }
   bool deQueue(int &x){  // 元素出队, x带回队头元素
        return remove(x, 1);
    }
};
// 派生类 Stack
class Stack:private LinearList{
public:
    bool push(int x){  // 元素x入栈,返回操作成功或失败
        return insert(x, 1); 
    }
    bool pop(int &x){  // 元素出栈,x带回栈顶元素
        return remove(x, 1);
    }
};

多态

多态的作用是使用一个接口调用多种方法,具体调用哪个函数,是在程序运行时决定的。实现多态,需要在派生类中定义与基类成员函数完全相同的方法签名(返回值、函数名、形参都完全一样)。作用在普通成员函数上,称为重置或覆盖。作用在虚成员函数上,称为实现。虚函数的前面都有virtual关键字,纯虚函数名末尾还有"=0"的标记,纯虚函数仅有定义,没有函数实现,当作接口使用。含有纯虚函数的类称为抽象类,不能创建对象,只能被继承。只有类的成员函数才能是虚函数,静态成员函数不能是虚函数,构造函数不能是虚函数,析构函数可以是虚函数。

cpp 复制代码
#include <iostream>
#include <math.h>
// 基类
class Figure{
public:
    virtual double getArea() = 0; // 纯虚函数
}; // 千万不要忘记这个分号
// 派生类 Rectangle
class Rectangle:public Figure{
protected:
    double height;
    double width;
public:
    Rectangle(){}
    Rectangle(double height, double width){
        this->height = height;
        this->width = width;
    }
    double getArea(){
        return height*width;
    }
};
// 派生类 Triangle
class Triangle:public Figure{
    double la;
    double lb;
    double lc;
public:
    Triangle(double la, double lb, double lc){
        this->la = la;
        this->lb = lb;
        this->lc = lc;
    }
    double getArea(){
        double s = (la+lb+lc)/2.0;
        return sqrt(s*(s-la)*(s-lb)*(s-lc));
    }
};
// 主函数
void main(){
    Figure *figures[2] = {new Triangle(2,3,3), new Rectangle(5,8)};
    for(int i=0; i<2; i++){
        std::cout << "figures[" << i << "] area=" << figures[i]->getArea() << std::endl;
        delete figures[i];
    }
}
相关推荐
zxctsclrjjjcph2 小时前
【高并发内存池】从零到一的项目之centralcache整体结构设计及核心实现
开发语言·数据结构·c++·链表
炯哈哈2 小时前
【上位机——MFC】单文档和多文档视图架构
开发语言·c++·mfc·上位机
利刃大大3 小时前
【网络编程】四、守护进程实现 && 前后台作业 && 会话与进程组
linux·网络·c++·网络编程·守护进程
oioihoii3 小时前
C++23 std::tuple与其他元组式对象的兼容 (P2165R4)
c++·链表·c++23
赵和范3 小时前
C++:书架
开发语言·c++·算法
LSL666_4 小时前
Java——多态
java·开发语言·多态·内存图
龙湾开发5 小时前
计算机图形学编程(使用OpenGL和C++)(第2版)学习笔记 05.纹理贴图
c++·笔记·学习·3d·图形渲染·贴图
yasuniko5 小时前
C++线程库
开发语言·c++
还有几根头发呀5 小时前
深入理解C/C++内存管理:从基础到高级优化实践
c++
zxctsclrjjjcph6 小时前
【递归、搜索和回溯】递归、搜索和回溯介绍及递归类算法例题
开发语言·c++·算法·力扣