How can I simulate interfaces in C++?

后端 未结 9 2107
时光说笑
时光说笑 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:03

    Interfaces in C++ are classes which have only pure virtual functions. E.g. :

    class ISerializable
    {
    public:
        virtual ~ISerializable() = 0;
        virtual void  serialize( stream& target ) = 0;
    };
    

    This is not a simulated interface, it is an interface like the ones in Java, but does not carry the drawbacks.

    E.g. you can add methods and members without negative consequences :

    class ISerializable
    {
    public:
        virtual ~ISerializable() = 0;
        virtual void  serialize( stream& target ) = 0;
    protected:
        void  serialize_atomic( int i, stream& t );
        bool  serialized;
    };
    

    To the naming conventions ... there are no real naming conventions defined in the C++ language. So choose the one in your environment.

    The overhead is 1 static table and in derived classes which did not yet have virtual functions, a pointer to the static table.

提交回复
热议问题