且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

你如何在C ++中声明一个接口?

更新时间:2022-06-20 02:16:16

要扩展 bradtgmurray ,您可能希望通过添加一个例外到接口的纯虚拟方法列表虚拟析构函数。这允许你将指针所有权传递给另一方,而不暴露具体的派生类。析构函数不需要做任何事情,因为接口没有任何具体成员。将函数定义为虚拟和内联都可能是矛盾的,但是相信我 - 不是。

To expand on the answer by bradtgmurray, you may want to make one exception to the pure virtual method list of your interface by adding a virtual destructor. This allows you to pass pointer ownership to another party without exposing the concrete derived class. The destructor doesn't have to do anything, because the interface doesn't have any concrete members. It might seem contradictory to define a function as both virtual and inline, but trust me - it isn't.

class IDemo
{
    public:
        virtual ~IDemo() {}
        virtual void OverrideMe() = 0;
};

class Parent
{
    public:
        virtual ~Parent();
};

class Child : public Parent, public IDemo
{
    public:
        virtual void OverrideMe()
        {
            //do stuff
        }
};

你不必为虚拟析构函数包含一个主体 - 事实证明一些编译器有麻烦优化一个空的析构函数,你***使用默认值。

You don't have to include a body for the virtual destructor - it turns out some compilers have trouble optimizing an empty destructor and you're better off using the default.