在 C++11 中声明接口的最佳方法

Best way to declare an interface in C++11(在 C++11 中声明接口的最佳方法)
本文介绍了在 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 中声明接口的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Polymorphic copy-constructor with type conversion(具有类型转换的多态复制构造函数)
Cast to a Child(铸造给孩子)
How to use virtual functions to achieve a polymorphic behavior in C++?(如何使用虚函数在 C++ 中实现多态行为?)
Polymorphism is not working with function return values of same data type (Base and Inherited class)(多态性不适用于相同数据类型(基类和继承类)的函数返回值)
Size of class with virtual function adds extra 4 bytes(具有虚函数的类的大小增加了额外的 4 个字节)
Right design pattern to deal with polymorphic collections of objects(正确的设计模式来处理对象的多态集合)