zoukankan      html  css  js  c++  java
  • 第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;
    };
  • 相关阅读:
    DataGridView如何获取某个数据
    扩展方法
    base和this关键字
    装箱和拆箱
    var,object和dynamic
    const和readonly
    react native回调函数刷新页面
    react native打包android,android9.0以上版本http请求不了怎么办?
    react native中android app怎样打包发布
    React Native 实现页面返回监听
  • 原文地址:https://www.cnblogs.com/huangdengtao/p/11985385.html
Copyright © 2011-2022 走看看