为了账号安全,请及时绑定邮箱和手机立即绑定

是否可以在C / C ++中模仿Go接口?

是否可以在C / C ++中模仿Go接口?

Go
ABOUTYOU 2021-05-03 12:16:36
在Go中,如果类型具有接口定义的所有方法,则可以将其分配给该接口变量,而无需显式继承。是否可以在C / C ++中模仿此功能?
查看完整描述

3 回答

?
慕尼黑的夜晚无繁华

TA贡献1864条经验 获得超6个赞

是的。您可以使用纯抽象类,也可以使用模板类来包装“实现”抽象类的类型,以便它们扩展抽象类。这是一个准系统示例:


#include <iostream>


// Interface type used in function signatures.

class Iface {

public:

        virtual int method() const = 0;

};


// Template wrapper for types implementing Iface

template <typename T>

class IfaceT: public Iface {

public:

        explicit IfaceT(T const t):_t(t) {}

        virtual int method() const { return _t.method(); }


private:

        T const _t;

};


// Type implementing Iface

class Impl {

public:

        Impl(int x): _x(x) {}

        int method() const { return _x; }


private:

        int _x;

};



// Method accepting Iface parameter

void printIface(Iface const &i) {

        std::cout << i.method() << std::endl;

}


int main() {

        printIface(IfaceT<Impl>(5));

}


查看完整回答
反对 回复 2021-05-10
  • 3 回答
  • 0 关注
  • 244 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信