如何在 C++ 中实现接口?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9756893/
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
how to implement Interfaces in C++?
提问by helpdesk
Possible Duplicate:
Preferred way to simulate interfaces in C++
可能的重复:
在 C++ 中模拟接口的首选方法
I was curious to find out if there are interfaces in C++ because in Java, there is the implementation of the design patterns mostly with decoupling the classes via interfaces. Is there a similar way of creating interfaces in C++ then?
我很想知道 C++ 中是否有接口,因为在 Java 中,设计模式的实现主要是通过接口将类解耦。那么在 C++ 中是否有类似的创建接口的方法?
回答by MD Sayem Ahmed
C++ has no built-in concepts of interfaces. You can implement it using abstract classeswhich contains only pure virtual functions. Since it allows multiple inheritance, you can inherit this class to create another class which will then contain this interface (I mean, object interface :) ) in it.
C++ 没有内置的接口概念。您可以使用仅包含纯虚函数的抽象类来实现它。由于它允许多重继承,您可以继承这个类来创建另一个类,然后在其中包含这个接口(我的意思是,对象接口 :) )。
An example would be something like this -
一个例子是这样的 -
class Interface
{
public:
Interface(){}
virtual ~Interface(){}
virtual void method1() = 0; // "= 0" part makes this method pure virtual, and
// also makes this class abstract.
virtual void method2() = 0;
};
class Concrete : public Interface
{
private:
int myMember;
public:
Concrete(){}
~Concrete(){}
void method1();
void method2();
};
// Provide implementation for the first method
void Concrete::method1()
{
// Your implementation
}
// Provide implementation for the second method
void Concrete::method2()
{
// Your implementation
}
int main(void)
{
Interface *f = new Concrete();
f->method1();
f->method2();
delete f;
return 0;
}
回答by Alok Save
There is no concept of interface in C++,
You can simulate the behavior using an Abstract class.
Abstract class is a class which has atleast one pure virtual function, One cannot create any instances of an abstract class but You could create pointers and references to it. Also each class inheriting from the abstract class must implement the pure virtual functions in order that it's instances can be created.
C++ 中没有接口的概念,
您可以使用抽象类来模拟行为。
抽象类是至少具有一个纯虚函数的类,不能创建抽象类的任何实例,但您可以创建指向它的指针和引用。此外,从抽象类继承的每个类都必须实现纯虚函数,以便可以创建它的实例。
回答by iammilind
Interface are nothing but a pure abstract classin C++. Ideally this interfaceclass
should contain only pure virtual
public methods and static const
data. For example:
接口只不过是C++ 中的一个纯抽象类。理想情况下,此接口class
应仅包含纯virtual
公共方法和static const
数据。例如:
class InterfaceA
{
public:
static const int X = 10;
virtual void Foo() = 0;
virtual int Get() const = 0;
virtual inline ~InterfaceA() = 0;
};
InterfaceA::~InterfaceA () {}