hel*_*esk 70 c++ interface concept
可能重复:
在C++中模拟接口的首选方法
我很想知道C++中是否有接口,因为在Java中,设计模式的实现主要是通过接口将类解耦.有没有类似的方法在C++中创建接口呢?
MD *_*med 108
C++没有内置的接口概念.您可以使用仅包含纯虚函数的抽象类来实现它.因为它允许多重继承,所以你可以继承这个类来创建另一个类,然后在其中包含这个接口(我的意思是,对象接口:)).
一个示例示例是这样的 -
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;
}
Run Code Online (Sandbox Code Playgroud)
iam*_*ind 12
接口只不过是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 () {}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
130330 次 |
最近记录: |