C++ 中的抽象类与接口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12854778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Abstract Class vs Interface in C++
提问by fatma.ekici
Possible Duplicate:
How do you declare an interface in C++?
可能的重复:
你如何在 C++ 中声明一个接口?
This is a general question about C++. As you know, there is no clear distinction between interface
and abstract class
in C++ unlike Java and C#. When would it be more preferrable to use an interface
instead of an abstract class
in C++? Could you give some examples?
这是关于 C++ 的一般问题。如你所知,有没有明确区分interface
并abstract class
不同于Java和C#在C ++。什么时候在 C++ 中使用 aninterface
而不是 an更可取abstract class
?你能举一些例子吗?
回答by Mr.C64
I assume that with interfaceyou mean a C++ class with only pure virtualmethods (i.e. without any code), instead with abstract classyou mean a C++ class with virtual methods that can be overridden, and some code, but at least one pure virtual methodthat makes the class not instantiable. e.g.:
我假设接口是指只有纯虚方法(即没有任何代码)的 C++ 类,而抽象类是指具有可以被覆盖的虚方法和一些代码,但至少有一个纯虚方法的 C++ 类这使得该类不可实例化。例如:
class MyInterface
{
public:
// Empty virtual destructor for proper cleanup
virtual ~MyInterface() {}
virtual void Method1() = 0;
virtual void Method2() = 0;
};
class MyAbstractClass
{
public:
virtual ~MyAbstractClass();
virtual void Method1();
virtual void Method2();
void Method3();
virtual void Method4() = 0; // make MyAbstractClass not instantiable
};
In Windows programming, interfacesare fundamental in COM. In fact, a COM component exports only interfaces (i.e. pointers to v-tables, i.e. pointers to set of function pointers). This helps defining an ABI(Application Binary Interface) that makes it possible to e.g. build a COM component in C++ and use it in Visual Basic, or build a COM component in C and use it in C++, or build a COM component with Visual C++ version X and use it with Visual C++ version Y. In other words, with interfaces you have high decoupling between client code and server code.
在 Windows 编程中,接口是COM 的基础。实际上,COM 组件仅导出接口(即指向v-tables 的指针,即指向函数指针集的指针)。这有助于定义一个ABI(应用程序二进制接口),例如,可以用 C++ 构建 COM 组件并在 Visual Basic 中使用它,或用 C 构建 COM 组件并在 C++ 中使用它,或使用 Visual C++ 构建 COM 组件版本 X 并将其与 Visual C++ 版本 Y 一起使用。换句话说,通过接口,您可以在客户端代码和服务器代码之间实现高度解耦。
Moreover, when you want to build DLL's with a C++ object-oriented interface (instead of pure C DLL's), as described in this article, it's better to export interfaces(the "mature approach") instead of C++ classes (this is basically what COM does, but without the burden of COM infrastructure).
此外,当您想使用 C++ 面向对象的接口(而不是纯 C DLL 的)构建 DLL 时,如本文所述,最好导出接口(“成熟方法”)而不是 C++ 类(这基本上是COM 可以,但没有 COM 基础结构的负担)。
I'd use an interfaceif I want to define a set of rules using which a component can be programmed, without specifying a concrete particular behavior. Classes that implement this interface will provide some concrete behavior themselves.
如果我想定义一组可以对组件进行编程的规则,而不指定具体的特定行为,我会使用接口。实现这个接口的类本身会提供一些具体的行为。
Instead, I'd use an abstract classwhen I want to provide some default infrastructure codeand behavior, and make it possible to client code to derive from this abstract class, overriding the pure virtual methods with some custom code, and completethis behavior with custom code. Think for example of an infrastructure for an OpenGL application. You can define an abstract class that initializes OpenGL, sets up the window environment, etc. and then you can derive from this class and implement custom code for e.g. the rendering process and handling user input:
相反,我会用一个抽象类,当我想提供一些默认的基础设施代码和行为,并有可能给客户代码派生从这个抽象类,覆盖了一些自定义代码的纯虚方法,并完成与此行为自定义代码。以 OpenGL 应用程序的基础设施为例。您可以定义一个抽象类来初始化 OpenGL,设置窗口环境等,然后您可以从这个类派生并实现自定义代码,例如渲染过程和处理用户输入:
// Abstract class for an OpenGL app.
// Creates rendering window, initializes OpenGL;
// client code must derive from it
// and implement rendering and user input.
class OpenGLApp
{
public:
OpenGLApp();
virtual ~OpenGLApp();
...
// Run the app
void Run();
// <---- This behavior must be implemented by the client ---->
// Rendering
virtual void Render() = 0;
// Handle user input
// (returns false to quit, true to continue looping)
virtual bool HandleInput() = 0;
// <--------------------------------------------------------->
private:
//
// Some infrastructure code
//
...
void CreateRenderingWindow();
void CreateOpenGLContext();
void SwapBuffers();
};
class MyOpenGLDemo : public OpenGLApp
{
public:
MyOpenGLDemo();
virtual ~MyOpenGLDemo();
// Rendering
virtual void Render(); // implements rendering code
// Handle user input
virtual bool HandleInput(); // implements user input handling
// ... some other stuff
};
回答by iammilind
interface
were primarily made popular by Java.
Below are the nature of interface
and its C++ equivalents:
interface
主要是由 Java 流行起来的。
以下是 的性质interface
及其 C++ 等价物:
interface
can contain only body-less abstract methods; C++ equivalent is purevirtual
methods, though they can/cannot have bodyinterface
can contain onlystatic final
data members; C++ equivalent isstatic const
data members which are compile time constants- Multiple
interface
can beimplement
ed by a Javaclass
, this facility is needed because a Javaclass
can inherit only 1class
; C++ supports multiple inheritance straight away with help ofvirtual
keyword when needed
interface
只能包含无主体的抽象方法;C++ 等价物是纯virtual
方法,尽管它们可以/不能有主体interface
只能包含static final
数据成员;C++ 等价物是static const
编译时常量的数据成员- Multiple
interface
可以被implement
一个 Java 编辑class
,这个工具是需要的,因为一个 Javaclass
只能继承 1class
;C ++virtual
在需要时通过关键字的帮助立即支持多重继承
Because of point 3 interface
concept was never formally introduced in C++. Still one can have a flexibility to do that.
由于第 3 点的interface
概念从未在 C++ 中正式引入。仍然可以灵活地做到这一点。
Besides this you can refer Bjarne's FAQon this topic.
除此之外,您可以参考 Bjarne关于此主题的常见问题解答。
回答by Will
An abstract class would be used when some common implementation was required. An interface would be if you just want to specify a contract that parts of the program have to conform too. By implementing an interface you are guaranteeing that you will implement certain methods. By extending an abstract class you are inheriting some of it's implementation. Therefore an interface is just an abstract class with no methods implemented (all are pure virtual).
当需要一些通用实现时,将使用抽象类。如果您只想指定程序的某些部分也必须遵守的约定,则接口将是。通过实现一个接口,您可以保证您将实现某些方法。通过扩展抽象类,您将继承其中的一些实现。因此,接口只是一个没有实现任何方法的抽象类(都是纯虚拟的)。
回答by user1740176
Pure Virtual Functions are mostly used to define:
纯虚函数主要用于定义:
a) abstract classes
a) 抽象类
These are base classes where you have to derive from them and then implement the pure virtual functions.
这些是基类,您必须从中派生,然后实现纯虚函数。
b) interfaces
b) 接口
These are 'empty' classes where all functions are pure virtual and hence you have to derive and then implement all of the functions.
这些是“空”类,其中所有函数都是纯虚拟的,因此您必须派生并实现所有函数。
Pure virtual functions are actually functions which have no implementation in base class and have to be implemented in derived class.
纯虚函数实际上是在基类中没有实现而必须在派生类中实现的函数。
回答by zhouchen
Please don't put members into an interface; though it's correct in phrasing. Please don't "delete" an interface.
请不要将成员放入接口中;虽然它的措辞是正确的。请不要“删除”一个接口。
class IInterface()
{
Public:
Virtual ~IInterface(){};
…
}
Class ClassImpl : public IInterface
{
…
}
Int main()
{
IInterface* pInterface = new ClassImpl();
…
delete pInterface; // Wrong in OO Programming, correct in C++.
}