c++ 如何编写接口类(interface)

接口类简介:

        接口是一系列抽象方法的声明,是一些方法特征的集合,这些方法都应该是抽象的,需要由具体的类去实现,然后第三方就可以通过这组抽象方法调用,让具体的类执行具体的方法。

用c++实现接口类时需要注意一下几点:

1、接口类中不应该声明成员变量,静态变量。

2、可以声明静态常量作为接口的返回值状态,需要在对应的cpp中定义并初始化,访问时需要使用"接口类型::静态常量名"访问

2、定义的接口方法使用virtual 修饰符 和 “=0” 修饰,表示该方法是纯虚的。

3、因为接口类是无法创建对象的,所以不应该编写构造函数和析构函数

IShape.h 

#ifndef ISHAPE_H
#define ISHAPE_H
 
 
class IShape
{
public:
    virtual int area() = 0;
    static const int MIN_AREA;
};
 
#endif // ISHAPE_H

 

IShape.cpp

#include "ishape.h"
 
const int IShape::MIN_AREA = 0;

 

IAction.h

#ifndef IACTION_H
#define IACTION_H
 
 
class IAction
{
public:
    virtual void run() = 0;
};
 
#endif // IACTION_H

 

Bird.h

#ifndef BIRD_H
#define BIRD_H
 
#include "iaction.h"
#include "ishape.h"
 
 
 
class Bird : public IShape, public IAction
{
public:
    Bird();
    ~Bird();
 
    // IAction interface
public:
    void run() override;
 
    // IShape interface
public:
    int area() override;
 
 
};
 
#endif // BIRD_H

 

Bird.cpp

#include "bird.h"
 
#include <iostream>
 
Bird::Bird()
{
    std::cout<<"小鸟出生了"<<std::endl;
}
 
Bird::~Bird()
{
    std::cout<<"小鸟挂掉了"<<std::endl;
}
 
void Bird::run()
{
    std::cout<<"小鸟飞呀飞呀"<<std::endl;
}
 
int Bird::area()
{
    std::cout<<"小鸟的形状像小鸡仔的形状"<<std::endl;
    std::cout<<IShape::MIN_AREA<<std::endl;            //这里访问常量是注意
}

 

main.cpp

#include "bird.h"
 
void doRun(IAction *object)
{
    object->run();
}
 
void getArea(IShape *object)
{
    object->area();
}
 
int main()
{
    Bird *bird = new Bird();
    doRun(bird);
    getArea(bird);
    delete bird;
    return 0;
}

 

执行效果:

 

参考:

https://www.cnblogs.com/lx753932159/p/5464406.html

https://blog.csdn.net/netyeaxi/article/details/80724557

 

posted @ 2019-03-06 10:03  h2z  阅读(17997)  评论(0编辑  收藏  举报