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++ 中实现接口?
基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
