我假设 interface 是指只有 纯虚拟 方法(即没有任何代码)的 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
};
在 Windows 编程中,接口是 COM 的基础。事实上,COM 组件只导出接口(即指向 v-tables 的指针,即指向函数指针集的指针)。这有助于定义一个 ABI(应用程序二进制接口),它可以让例如在 C++ 中构建 COM 组件并在 Visual Basic 中使用,或者在 C 中构建 COM 组件并在 C++ 中使用,或者在 Visual C++ 版本 X 中构建 COM 组件并在 Visual C++ 版本 Y 中使用。
换句话说,通过接口,您可以在客户端代码和服务器代码之间实现高度解耦。
此外,当您想要使用 C++ 面向对象的接口(而不是纯 C DLL)构建 DLL 时,如 this article 中所述,最好导出 interfaces(“成熟的方法") 而不是 C++ 类(这基本上是 COM 所做的,但没有 COM 基础结构的负担)。
如果我想定义一组可以用来编程组件的规则,而不指定具体的特定行为,我会使用 接口。实现这个接口的类会自己提供一些具体的行为。
相反,当我想提供一些默认的基础架构代码和行为时,我会使用一个抽象类,并让客户端代码可以从这个抽象派生类,用一些自定义代码覆盖纯虚方法,并使用自定义代码完成此行为。
以 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
};