• 第52课.c++中的抽象类和接口


    1.什么是抽象类

    a.可用于表示现实世界中的抽象概念
    b.是一种只能定义类型,而不能产生对象的类
    c.只能被继承被重写相关函数 (不能创建对象,只能用于继承,可以用来定义指针)
    d.直接特征是相关函数没有完整的实现

    2.抽象类与纯虚函数

    a.c++语言中没有抽象类的概念
    b.c++中通过纯虚函数实现抽象类
    c.纯虚函数是指只定义原型的成员函数
    d.一个c++类中只要存在纯虚函数这个类就成为了抽象类
    eg.

    纯虚函数语法规则:

    class Shape
    {
    public:
        virtaul double area () = 0;
    };
    //这里" = 0"用于告诉编译器当前是声明纯虚函数,因此不需要定义函数体
    

    eg:

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class Shape
    {
    public:
        virtual double area () = 0;
    };
    
    class Rect : public Shape
    {
        int ma;
        int mb;
    public:
        Rect (int a, int b)
        {
            ma = a;
            mb = b;
        }
        
        double area ()
        {
            return ma * mb;
        }
    };
    
    class Circle : public Shape
    {
        int mr;
    public:
        Circle (int r)
        {
            mr = r;
        }
        
        double area ()
        {
            return 3.14 * mr * mr;
        }
    };
    
    void area (Shape* p)            // 抽象类可以定义指针
    {
        double r = p->area();       // Shape的纯虚函数,没有实现。但这里调用的是子类中实现的虚函数
                                    // 因为子类中实现了父类中的纯虚函数,所以这里才能调用
        cout << "r = " << r << endl;
    }
    
    int main()
    {
        Rect rect (1, 2);
        Circle circle(10);
        
        area(&rect);
        area(&circle);
        
        return 0;   
    }
    

    3.接口

    a.类中没有定义任何的成员变量
    b.所有的成员函数都是公有的
    c.所有的成员函数都是纯虚函数
    d.接口是一种特殊的抽象类

    eg:

    class Channel
    {
    public:
        virtual bool open () = 0;
        virtual void close () = 0;
        virtual bool send (char* buf, int len) = 0;
        virtual int receive (char* buf, int len); = 0;
    };
  • 相关阅读:
    从零开始学架构(三)UML建模
    【网址收藏】博客园主题美化
    完美解决国内访问GitHub速度太慢的难题
    SpringBoot+slf4j线程池全链路调用日志跟踪 二
    SpringBoot+slf4j实现全链路调用日志跟踪 一
    2021年java最全面试宝典【核心知识整理】
    [中级]系统集成项目管理工程师历年真题及参考答案
    线程池ThreadPoolExecutor最全实战案例
    大厂git分支管理规范:gitflow规范指南
    IdentityServer4
  • 原文地址:https://www.cnblogs.com/huangdengtao/p/11985385.html
Copyright © 2020-2023  润新知