接口隔离示例 C++

Interface segregation example C++

我正在查看 oodesign website 接口隔离示例

我理解了这个例子并用 C++ 写了下面的代码,

#include <iostream>

using namespace std;

class IWorkable {
public: 
    virtual void work() = 0;
};

class IFeedable{
public:
    virtual void eat() = 0;
};

// interface segregation principle - good example
class IWorker : public IFeedable, public IWorkable {
};

class Worker : public IWorkable, public IFeedable
{
public:
    void work() {
        cout << "working" <<endl;
    }

    void eat() {
        cout << "eating in launch break" <<endl;
    }
};

class SuperWorker : public IWorkable, public IFeedable{
public:
    void work() {
        cout << "working much more" << endl;
    }
    void eat() {
        cout << "eating in launch break" <<endl;
    }
};

class Robot :public IWorkable{
public:
    void work() {
        cout << "Robot working" <<endl;
    }
};

class Manager {
    IWorkable *worker;

public :
    void setWorker(IWorkable *w) {
        worker = w;
    }

    void manage() {
        worker->work();
    }
};

int main()
{
    IWorkable * w1 = new Worker();
    IWorkable * sw1 = new SuperWorker();
    IWorker *w2;
    Manager m1;
    m1.setWorker(w1);
    m1.manage();

    //When worker wants he can eat
    w2 = dynamic_cast<IWorker*>(w1);
    w2->eat();

    return 0;
}

当我 运行 以上代码时,我在 w2->eat();

处遇到分段错误

我的猜测是代码仅将 IWorkable 的指针转换为 IWorker,这是行不通的,因为 IWorkable 没有 eat 方法。

如果是这样,这种情况下的解决方案是什么? 任何 suggestion/pointer 都会有所帮助。

注意:我正在 C++98 中尝试,但我愿意在 C++11/14/17 中学习新方法。

您正在访问指针 w2 而未分配它。由于指针值默认为未定义值,因此无法保证它指向有效对象。参见:https://en.wikipedia.org/wiki/Dangling_pointer#Cause_of_wild_pointers

您的 dynamic_cast 正在 returning NULL,因为 Worker 不继承 IWorker。通过使用我假设您想要的继承,这可以正常工作。

class Worker : public IWorker { /* your same implmenetations */ };