官术网_书友最值得收藏!

Understanding interfaces

An interface implements no functions, but simply declares the methods that the class will support. Then, all of the derived classes will do the implementation. In this way, the developer will have more freedom to implement the functions to fit each instance, while having things work correctly due to the nature of using an object-oriented language.

Interfaces may contain only static final variables, and they may contain only abstract methods, which means that they cannot be implemented within the class. However, we can have interfaces that inherit from other interfaces. When creating theses classes, we can implement whatever number of interfaces we want to. This allows us to make classes become even more polymorphic but, by doing so, we are agreeing that we will implement each of the functions defined in the interface. Because a class that implements an interface extends from that base class, we would say that it has an IS-A relationship with that type.

Now, interfaces have one disadvantage, and that's the fact that they tend to require a lot of coding to implement each of the different versions as needed, but we will talk about ways to adjust and/or fix this issue over the course of this book.

In C++, there isn't an official concept of interfaces, but you can simulate the behavior of interfaces by creating an abstract class.

Here's a simple example of an interface, and an implementation of it:

class Enemy 
{
public:
virtual ~Enemy(void) {/*Empty virtual destructor*/}
virtual void DisplayInfo(void) = 0;
virtual void Attack(void) = 0;
virtual void Move(void) = 0;
};

class FakeEnemy: public Enemy
{
public:
virtual void DisplayInfo(void)
{
M5DEBUG_PRINT("I am a FAKE enemy");
}

virtual void Attack(void)
{
M5DEBUG_PRINT("I cannot attack");
}

virtual void Move(void)
{
M5DEBUG_PRINT("I cannot move");
}
};

And here's how it looks in UML:

主站蜘蛛池模板: 砀山县| 犍为县| 隆子县| 铜山县| 江城| 上栗县| 石狮市| 凤城市| 册亨县| 年辖:市辖区| 阜城县| 铜梁县| 大城县| 康定县| 临沂市| 东乡| 遂平县| 柳江县| 启东市| 曲水县| 龙江县| 施甸县| 怀来县| 安远县| 安宁市| 五台县| 三门峡市| 沐川县| 宝兴县| 油尖旺区| 屯门区| 丹寨县| 丹江口市| 革吉县| 呈贡县| 临桂县| 亳州市| 建昌县| 和田县| 昂仁县| 龙游县|