如何在 C++ 中模拟接口? [英] How can I simulate interfaces in C++?
问题描述
由于 C++ 缺少 Java 和 C# 的 interface
特性,那么在 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屋!