抽象类和接口

抽象类:

  1. 表示现实世界的抽象概念(动物对于猪)

  2. 不能用来创建对象,只能用来定义类型或继承(必须重写相关函数)或定义指针

  3. 抽象类内部函数没有具体实现

抽象类的实现:

  1. 当类中定义了纯虚函数,这个类就是抽象类。

  2.纯虚函数是只定义了函数声明的虚函数

抽象类语法:

class picture       // 抽象类
{
public:
    virtual double area() = 0;   // 纯虚函数
};

抽象类的多态:

#include <iostream>
#include <string>

using namespace std;

class animal       // 抽象类
{
public:
    virtual void which_kind() = 0;   // 纯虚函数
};

class  cow : public animal  // 继承抽象类
{
public:
    void which_kind()
    {
     cout <<  "cow !" << endl;
    }
};

class sheep : public animal // 继承抽象类
{
public:
    void which_kind()   // which_kind被重写后变成虚函数
    {
     cout <<  "sheep !" << endl;
    }
};

void which_kind(animal* p)  // 抽象类可以定义指针
{
    p->which_kind(); 
}

int main()
{
    cow c;
    sheep s;
    which_kind(&c);  // 抽象类也具有多态性
    which_kind(&s);    
    return 0;
}

注意:

  1. 子类必须实现全部继承的抽象类的的纯虚函数,否则子类也将是抽象类

  2. 纯虚函数被重写后变成虚函数

接口:

  1. 类中没有定义任何成员变量

  2. 类中函数全是公有函数并且全是纯虚函数

  3.接口是一种特殊的抽象类

#include <iostream>
#include <string>

using namespace std;

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;
};

int main()
{
    return 0;
}
原文地址:https://www.cnblogs.com/zsy12138/p/10853154.html