How can I simulate interfaces in C++?

后端 未结 9 2123
时光说笑
时光说笑 2020-12-04 19:22

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 o

9条回答
  •  盖世英雄少女心
    2020-12-04 20:28

    Since C++ has multiple inheritance unlike C# and Java, yes you can make a series of abstract classes.

    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() { }
    };
    

    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.

提交回复
热议问题