C++ question: feature similar to Obj-C protocols?

我的未来我决定 提交于 2020-01-01 04:25:25

问题


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. Table view, which has a function setDelegate(Protocol *delegate)
  2. Delegate of class Class, but implementing the protocol 'Protocol'
  3. Delegate of class Class2, also implementing 'Protocol'
  4. setDelegate(objOfClass) and setDelegate(objOfClass2) are both valid

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


回答1:


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) { }
};


来源:https://stackoverflow.com/questions/3130588/c-question-feature-similar-to-obj-c-protocols

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!