Как вы вводите зависимости в классе, который зависит от класса, который зависит от другого класса в C ++? - PullRequest
1 голос
/ 31 марта 2020

Я пытаюсь внедрить внедрение зависимостей в проект C ++. Однако из-за структуры зависимостей я получаю ошибку сегментации, которую не могу устранить.

В качестве примера я создал следующие классы и интерфейсы. У меня есть класс с именем MyClass, который зависит от зависимости. Зависимость зависит от OtherDependency. Чтобы обеспечить надлежащее тестирование, я наследую зависимости от интерфейса, то есть IDependency и IOtherDependency. OtherDependency имеет функцию some_function ().

В main. cpp Я создаю экземпляр MyClass и затем пытаюсь вызвать some_function (). К сожалению, это приводит к ошибке сегментации:

Segmentation fault (core dumped)

MyClass.h:

#ifndef MYCLASS_H
#define MYCLASS_H

#include "IDependency.h"

class MyClass
{
public:
    MyClass(IDependency *dependency);
    ~MyClass();

    IDependency *_dependency = nullptr;
};

#endif

MyClass. cpp:

#include "MyClass.h"

#include <iostream>

MyClass::MyClass(IDependency *dependency) : _dependency(dependency) {}

MyClass::~MyClass() {}

Dependency.h:

#ifndef DEPENDENCY_H
#define DEPENDENCY_H

#include "IDependency.h"
#include "IOtherDependency.h"

class Dependency : public IDependency
{
public:
    Dependency(IOtherDependency *other_dependency);
    ~Dependency();

    IOtherDependency *_other_dependency = nullptr;
};

#endif

Зависимость. cpp:

#include "Dependency.h"

#include <iostream>

Dependency::Dependency(IOtherDependency *other_dependency) : _other_dependency(other_dependency) {}

Dependency::~Dependency() {}

IDependency.h:

#ifndef IDEPENDENCY_H
#define IDEPENDENCY_H

#include "IOtherDependency.h"

class IDependency
{
public:
    IOtherDependency *_other_dependency;
};

#endif

OtherDependency.h:

#ifndef OTHERDEPENDENCY_H
#define OTHERDEPENDENCY_H

#include "IOtherDependency.h"

class OtherDependency : public IOtherDependency
{
public:
    OtherDependency();
    ~OtherDependency();

    void some_function();
};

#endif

OtherDependency . cpp:

#include "OtherDependency.h"

#include <iostream>

OtherDependency::OtherDependency() {}

OtherDependency::~OtherDependency() {}

void OtherDependency::some_function()
{
    std::cout << "I am OtherDependency." << std::endl;
}

IOtherDependency.h:

#ifndef IOTHERDEPENDENCY_H
#define IOTHERDEPENDENCY_H

class IOtherDependency
{
public:
    virtual void some_function() = 0;
};

#endif

main. cpp:

int main()
{
    OtherDependency *other_dependency = new OtherDependency;
    Dependency *dependency = new Dependency(other_dependency);
    MyClass my_class(dependency);

    my_class._dependency->_other_dependency->some_function();
}

Что я делаю неправильно / я делаю нужно поменять?

1 Ответ

2 голосов
/ 31 марта 2020

У вас есть две переменные с именем _other_dependency: одна в IDependency, другая в Dependency. Конструктор Dependency инициализировал последний, в то время как в классе IDependency сохраняется значение по умолчанию nullptr.

Когда вы обращаетесь к my_class._dependency->_other_dependency, other_dependency будет таким же, как в IDependency, потому что _dependency указывает на базовый класс.

Один из способов исправить это - удалить other_dependency из Dependency и передать значение из конструктора Dependency в IDependency для правильной инициализации его член.

...