C++ 问题:类似于 Obj-C 协议的特性? [英] C++ question: feature similar to Obj-C protocols?

查看:58
本文介绍了C++ 问题:类似于 Obj-C 协议的特性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯在我的代码中使用 Objective-C 协议;它们在很多方面都令人难以置信.但是,在 C++ 中,我不确定如何完成同样的事情.举个例子:

I'm used to using Objective-C protocols in my code; they're incredible for a lot of things. However, in C++ I'm not sure how to accomplish the same thing. Here's an example:

  1. 表视图,它有一个函数 setDelegate(Protocol *delegate)
  2. 类 Class 的委托,但实现了协议Protocol"
  3. Class2 类的代表,也实现了协议"
  4. setDelegate(objOfClass) 和 setDelegate(objOfClass2) 都是有效的

在 Obj-C 中这很简单,但我不知道如何在 C++ 中做到这一点.甚至有可能吗?

In Obj-C this is simple enough, but I can't figure out how to do it in C++. Is it even possible?

推荐答案

基本上,不是协议"而是具有纯虚函数的基类",有时在其他语言中也称为接口.

Basically, instead of "Protocol" think "base class with pure virtual functions", sometimes called an interface in other languages.

class Protocol
{
public:
    virtual void Foo() = 0;
};

class Class : public Protocol
{
public:
    void Foo() { }
};

class Class2 : public Protocol
{
public:
    void Foo() { }
};

class TableView
{
public:
    void setDelegate(Protocol* proto) { }
};

这篇关于C++ 问题:类似于 Obj-C 协议的特性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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