类的C ++循环依赖关系(Singleton)

我在编译具有循环依赖性的类时遇到问题,并且我找不到编译代码的方法

主要问题出现在相互依赖的类链中

例如我有6个头文件(类)(A,B,C,D,E,F)

E中包含的A

F,D包含在A

E包含在F,D

现在我有一个循环,无法修复它

我先简化问题,然后创建简单的示例来说明我的确切问题

A.h

#ifndef A_H
#define A_H
#include "B.h"

class A
{
public:
    static A& getInstance()
    {
        static A  instance; 
        return instance;
    }
    int i;
    int sum()
    {
        return i+B::getInstance().j;
    }
private:
    A() {}
};
#endif

B.h
#ifndef B_H
#define B_H
#include "A.h"

class B
{
public:
    static B& getInstance()
    {
        static B  instance; 
        return instance;
    }
    int j;
    int sum()
    {
        return j+A::getInstance().j;
    }
private:
    B() {}
};
#endif
main.cpp

#include "A.h"
#include "B.h"
#include <iostream>
int  main()
{

    A::getInstance().i=1;
    B::getInstance().j=2;
    int t1=A::getInstance().sum();
    int t2=B::getInstance().sum();
    std::cout<<t1<<std::endl;
    std::cout<<t2<<std::endl;
    return 0;
}


g++ main.cpp
In file included from A.h:3:0,from main.cpp:1:
B.h: In member function ‘int B::sum()’:
B.h:17:12: error: ‘A’ has not been declared
   return j+A::getInstance().j;

有什么方法或解决方案可以解决这个问题吗?

oji6695 回答:类的C ++循环依赖关系(Singleton)

如果由于某种原因无法使用.cpp文件,可以执行以下操作:

a.h

#pragma once

class A {
public:
    static A& getInstance();
    int i;
    int sum();

private:
    A();
};

a_impl.h

#pragma once
#include "a.h"
#include "b.h"

inline A& A::getInstance() {
    static A instance;
    return instance;
}

inline int A::sum() {
    return i + B::getInstance().j;
}

inline A::A() {
}

b.h

#pragma once

class B {
public:
    static B& getInstance();
    int j;
    int sum();

private:
    B();
};

b_impl.h

#pragma once
#include "a.h"
#include "b.h"

inline B& B::getInstance() {
    static B instance;
    return instance;
}

inline int B::sum() {
    return j + A::getInstance().i;
}

inline B::B() {
}

然后首先包含声明a.hb.h,然后包括实现a_impl.hb_impl.h

#include "a.h"
#include "b.h"
#include "a_impl.h"
#include "b_impl.h"
#include <iostream>

int main() {
    A::getInstance().i = 1;
    B::getInstance().j = 2;
    int t1 = A::getInstance().sum();
    int t2 = B::getInstance().sum();
    std::cout << t1 << std::endl;
    std::cout << t2 << std::endl;
}

现在它将编译。在这个特定示例中,B(或A)可以在类定义中实现(因此,没有b_impl.h)。为了对称起见,我将两个类的声明和定义都分开了。

本文链接:https://www.f2er.com/3042627.html

大家都在问