c++ - 循环依赖,即使类是前向声明的

标签 c++ visual-studio-2015 circular-dependency

有一个非常奇怪的问题,即使向前声明受影响的类也无法解决循环依赖。

如您所见,这两个类都是前向声明的。那么有什么解释吗?没有定义任何一个类的符号。很明显是循环依赖错误。

提前感谢您的建议。

LogBackend.h

#ifndef LOGGER_BACKEND_H
#define LOGGER_BACKEND_H

#include "Logger.h"
#include <string>

namespace se {
    class Logger;
    class LogBackend {
    public:

        LogBackend() { }
        explicit LogBackend(const std::string& name);
        virtual ~LogBackend() { }

        virtual void log(const Logger::Level l, const std::string& text) = 0;

        /*
         Method interface
        */

        bool valid();
        std::string getName();

    protected:
        bool m_valid = true;
        std::string m_name;
    };
}
#endif

注意:有LogBackend的派生类

Logger.h

#ifndef LOGGER_H
#define LOGGER_H

#include "LogBackend.h"
#include <string>
#include <sstream>
#include <vector>
#include <glew/glew.h>

namespace se {
    class LogBackend;
    class Logger {
    public:

        enum class Level { WARNING, INFO, EXCEPTION, SEVERE };
        static std::string to_string(Level l);

        static void add(const LogBackend& backend);

        /*
         Methods
        */

    private:
        static std::vector<LogBackend> m_backends;
    };
}
#endif

最佳答案

由于您正在使用,在 Logger.h 中有一个 std::vector<LogBackend>前向声明是不够的,除非您将其更改为 std::vector<LogBackend *>std::vector<std::shared_ptr<LogBackend>>

LogBackend 有类似的问题,您正在使用 Logger::Level,因为您只是转发声明的 Logger,所以它不可用。

我建议您通过使用指向 LogBackend 的指针来打破 Logger.h 中的依赖性

关于c++ - 循环依赖,即使类是前向声明的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34205846/

相关文章:

c++ - 如何在 minGW 的 Eclipse 中禁用未使用的变量警告?

c# - 如何绑定(bind)到 UWP 中的附加属性?

c# - C# 中两个项目中的循环依赖

mysql - 避免循环依赖: MySQL/Entity Framework

c++ - 在不指定模板参数的情况下引用非依赖名称

c++ - 我在 C++ 中创建阻塞队列 vector 时遇到问题

c++ - CGAL 中的 Fixed_precision_nt 数字类型发生了什么变化?

c# - ASP.Net 5 app.UseStaticFiles() 错误

visual-studio-2015 - Visual Studio 2015 - "Recently Finished"代码审查未显示结果

c++ - C++ 模块中的前向声明 (MSVC)