how to implement Interfaces in C++?(如何在 C++ 中实现接口?)
问题描述
可能的重复:
在 C++ 中模拟接口的首选方法
我很想知道 C++ 中是否有接口,因为在 Java 中,设计模式的实现主要是通过接口将类解耦.那么在 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++ 没有内置的接口概念.您可以使用仅包含 纯虚函数.因为它允许多重继承,你可以继承这个类来创建另一个类,然后在其中包含这个接口(我的意思是,对象接口 :)).
C++ has no built-in concepts of interfaces. You can implement it using abstract classes which 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.
一个例子是这样的 -
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;
}
这篇关于如何在 C++ 中实现接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C++ 中实现接口?
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
