如何在C ++中模拟接口? [英] How can I simulate interfaces in C++?
问题描述
由于C ++缺少Java和C#的接口
特性,在C ++类中模拟接口的首选方法是什么?我的猜测是抽象类的多重继承。
在内存开销/性能方面有什么影响?
这些模拟接口是否有任何命名约定,例如 SerializableInterface
?
Since C++ lacks the interface
feature of Java and C#, what is the preferred way to simulate interfaces in C++ classes? My guess would be multiple inheritance of abstract classes.
What are the implications in terms of memory overhead/performance?
Are there any naming conventions for such simulated interfaces, such as SerializableInterface
?
推荐答案
因为C ++有多重继承,不像C#和Java,是的,你可以做一系列抽象类。
Since C++ has multiple inheritance unlike C# and Java, yes you can make a series of abstract classes.
;但是,我喜欢在类名之前加上一个I。
As for convention, it is up to you; however, I like to precede the class names with an I.
class IStringNotifier
{
public:
virtual void sendMessage(std::string &strMessage) = 0;
virtual ~IStringNotifier() { }
};
在C#和Java之间的比较方面,性能没有什么可担心的。基本上你只是有一个查找表为您的函数或vtable的开销,就像任何种类的继承与虚拟方法将给出。
The performance is nothing to worry about in terms of comparison between C# and Java. Basically you will just have the overhead of having a lookup table for your functions or a vtable just like any sort of inheritance with virtual methods would have given.
这篇关于如何在C ++中模拟接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!