在C ++中使用抽象类进行依赖注入

时间:2017-07-04 05:19:59

标签: c++

引用this Stackoverflow问题,我无法弄清楚使用c ++风格的接口实现DI的同样问题,即抽象类。而不是碰到旧线程我创建了这个。编译器抛出最后一行的错误。

{{1}}

2 个答案:

答案 0 :(得分:3)

  1. 在C ++类中,默认情况下,成员是私有的。 您应在public:之前指定virtual void DoWork() = 0;

  2. 默认情况下,C ++继承是私有的(使用class关键字时)。而不是: IService,请尝试: public IService。查看私有,受保护,公共继承here之间的差异。

  3. _service->DoWork();的函数体在哪里?

答案 1 :(得分:3)

我相信这就是你想要的:

#include <iostream>
using namespace std;

struct IService {
    virtual ~IService() = default; // Remember about virtual dtor to avoid memory leaks!
    virtual void DoWork() = 0;
    virtual bool IsRunning() = 0;
};

class ClientA : public IService {
    void DoWork() {
        std::cout << "Work in progress inside A" << endl;
    }
    bool IsRunning() { 
        return true; 
    }
};

class ClientB : public IService {
    void DoWork() {
        std::cout << "Work in progress inside B" << endl;
    }
    bool IsRunning() {
        return true;
    }
};

class Server {
    IService* _service;
public:
    Server(IService* service) : _service(service)
    { }

    void doStuff() {
        _service->DoWork();
    }
};

int main() {

    ClientA a;
    ClientB b;
    Server sa(&a), sb(&b);
    cout << "ServerA: " << endl;
    sa.doStuff();
    cout << "ServerB: " << endl;
    sb.doStuff();
    return 0;
}

Ideone

您需要熟悉C ++中访问说明符的概念。见here