你如何在 C++ 中声明一个接口? [英] How do you declare an interface in C++?

查看:33
本文介绍了你如何在 C++ 中声明一个接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何设置代表接口的类?这只是一个抽象基类吗?

How do I setup a class that represents an interface? Is this just an abstract base class?

推荐答案

通过 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.

这篇关于你如何在 C++ 中声明一个接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆