在 C++11 中声明接口的最佳方式 [英] Best way to declare an interface in C++11

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

问题描述

众所周知,有些语言有接口的概念.这是Java:

As we all know, some languages have the notion of interfaces. This is Java:

public interface Testable {
  void test();
}

如何在 C++(或 C++11)中以最紧凑的方式实现这一点,并且代码噪音很小?我很欣赏一个不需要单独定义的解决方案(让标题就足够了).这是一种非常简单的方法,即使我也觉得有问题 ;-)

How can I achieve this in C++ (or C++11) in most compact way and with little code noise? I'd appreciate a solution that wouldn't need a separate definition (let the header be sufficient). This is a very simple approach that even I find buggy ;-)

class Testable {
public:
  virtual void test() = 0;
protected:
  Testable();
  Testable(const Testable& that);
  Testable& operator= (const Testable& that);
  virtual ~Testable();
}

这只是开始......而且已经比我想要的更长了.如何改进它?也许在 std 命名空间中的某个地方有一个专门为此创建的基类?

This is only the beginning.. and already longer that I'd want. How to improve it? Perhaps there is a base class somewhere in the std namespace made just for this?

推荐答案

关于:

class Testable
{
public:
    virtual ~Testable() { }
    virtual void test() = 0;
}

在 C++ 中,这对子类的可复制性没有影响.所有这一切都表明孩子必须实现 test (这正是您想要的接口).您无法实例化此类,因此您不必担心任何隐式构造函数,因为它们永远无法作为父接口类型直接调用.

In C++ this makes no implications about copyability of child classes. All this says is that the child must implement test (which is exactly what you want for an interface). You can't instantiate this class so you don't have to worry about any implicit constructors as they can't ever be called directly as the parent interface type.

如果您希望强制子类实现析构函数,您也可以将其设为纯析构函数(但您仍然必须在接口中实现它).

If you wish to enforce that child classes implement a destructor you can make that pure as well (but you still have to implement it in the interface).

另请注意,如果您不需要多态析构,您可以选择将析构函数设置为非虚拟的.

Also note that if you don't need polymorphic destruction you can choose to make your destructor protected non-virtual instead.

这篇关于在 C++11 中声明接口的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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