这是一个关于C++的一般性问题。正如你所知,在C++中,与Java和C#不同,没有明确区分“接口”和“抽象类”。在什么情况下使用“接口”而不是“抽象类”会更好呢?你能给出一些例子吗?该怎样声明一个C++中的接口?(参考链接:How do you declare an interface in 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表的指针,即一组函数指针的指针)。这有助于定义一个ABI(应用程序二进制接口),使得可以在C++中构建COM组件并在Visual Basic中使用它,在C中构建COM组件并在C++中使用它,或使用Visual C++版本X构建COM组件并在版本Y中使用它。// 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
};
void Method3();
的声明使得这个类成为抽象类,因为它没有被声明为虚函数吗? - Celeritasinterface
最初是由Java流行起来的。
以下是interface
及其C ++等效项的性质:
interface
只能包含无内容的抽象方法; C++等效项是纯虚方法,但它们可以/不能有内容。interface
只能包含static final
数据成员; C++
等效项是静态常量数据成员,这些成员是编译时常数。class
可以实现多个interface
,因为需要这种功能,因为Javaclass
只能继承1个class
; C++支持使用virtual
关键字直接进行多重继承。由于第3点,interface
概念从未在C ++中正式引入。尽管如此,仍然可以具有灵活性。
此外,您可以参考Bjarne关于此主题的FAQ。
virtual
关键字进行多重继承。实际上,良好的设计使用多重继承避免使用virtual
关键字(如果可能的话,他们会尝试完全避免多重继承)。 - Samaursanew
创建一个指针,析构函数总是会被调用(由编译器隐式放置)。因此对于纯虚析构函数,必须定义一个函数体,除非没有创建对象。在C++03中,所有方法都是静态的class
是一个很好的使用案例,其中不需要定义纯虚析构函数的函数体。但是在C++11中可以通过使用= delete
来实现。 - iammilind当需要一些共同的实现时,可以使用抽象类。如果您只想指定程序的某些部分必须遵守的契约,则可以使用接口。通过实现接口,您保证将实现某些方法。通过扩展抽象类,您继承了其中的一些实现。因此,接口只是一个没有实现任何方法(都是纯虚拟的)的抽象类。
纯虚函数主要用于定义:
a) 抽象类
这些是基类,您必须从它们派生并实现纯虚函数。
b) 接口
这些是“空”的类,其中所有函数都是纯虚函数,因此您必须派生并实现所有函数。
纯虚函数实际上是在基类中没有实现的函数,并且必须在派生类中实现。
class IInterface()
{
Public:
Virtual ~IInterface(){};
…
}
Class ClassImpl : public IInterface
{
…
}
Int main()
{
IInterface* pInterface = new ClassImpl();
…
delete pInterface; // Wrong in OO Programming, correct in C++.
}
std::make_unique
或std::make_shared
代替。这将防止内存泄漏和其他常见错误。 - Flip