接口如在java中的c ++? [英] Interface as in java in c++?

查看:134
本文介绍了接口如在java中的c ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

有人问我一个qustion:在C ++没有接口像java中,但事件然后你可以实现他们在c + +,你会怎么做?

Somebody asked me a qustion: "In C++ there are no interfaces like in java. But event then you could realize them in c++, how would you do that?"

如何?我将使用虚拟方法创建一个类。这将看起来像一个接口在java或?

How? I would make a class with virtual methods. That would be look like an interface as in java or?

谢谢

推荐答案

您可以使用多个继承在C ++中创建接口。

You can create interfaces in C++ using multiple inheritance.

您创建一个纯虚拟的基类(所有函数= 0),然后您的类继承

You create a base class which is pure virtual (all functions =0) and then your classes inherit from this.

多继承意味着你可以继承自己喜欢的这些。

Multiple inheritance means you can inherit from as many of these as you like.

// Interface definition
class ISomethingable
{
public:
    virtual ~ISomethingable() {}
    virtual void DoSomething() = 0;    
}

// Your code
class MyClass : public ISomethingable
{
public:
    void DoSomething()
    {
         // Do something concrete.
    }
}

另请参阅:如何在C ++中声明接口?

这篇关于接口如在java中的c ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆