问题描述
众所周知,有些语言有接口的概念.这是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 中声明接口的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!