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

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

问题描述

我们都知道,一些语言有接口的概念。这是Java:

  public interface Testable {
void test();
}

如何在C ++(或C ++ 11)紧凑的方式和很少的代码噪声?我会感谢一个解决方案,不需要一个单独的定义(让标题是足够的)。这是一个非常简单的方法,即使我发现bug ;-)

  class Testable {
public:
virtual void test()= 0;
protected:
Testable();
Testable(const Testable& that);
可测试& operator =(const Testable& that);
virtual〜Testable();
}

这只是开始..如何提高呢?

解决方案

关于:



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

在C ++中,这不会影响子类的可复制性。所有这些说的是,孩子必须实现 test (这正是你想要的接口)。您不能实例化此类,因此您不必担心任何隐式构造函数,因为它们不能直接作为父接口类型调用。



如果你希望强制子类实现一个析构函数,你可以使纯的(但是你仍然必须在界面中实现它)。



还要注意,如果你不需要多态性破坏,你可以选择使你的析构器保护非虚拟。


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

public interface Testable {
  void test();
}

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

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?

解决方案

What about:

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

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天全站免登陆