簡體   English   中英

C++ 類的循環依賴(Singleton)

[英]C++ cyclic dependency of classes (Singleton)

我在編譯具有循環依賴的類時遇到問題,我找不到編譯我的代碼的方法

主要問題出現在相互依賴的類鏈中

例如我有 6 個頭文件(類)(A、B、C、D、E、F)

A 包含在 E 中

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;

有沒有辦法或解決方案來解決這個問題?

如果由於某種原因不能使用.cpp文件,您可以這樣做:

ah

#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() {
}

bh

#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() {
}

然后首先包含聲明ahbh ,然后實現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 )。 為了對稱起見,我將兩個類的聲明和定義分開。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM