【问题标题】:C++: Circular dependency with static membersC++:具有静态成员的循环依赖
【发布时间】:2021-09-03 08:58:18
【问题描述】:

我有以下代码:

class B;

class A {
public:
    static int somethingStatic;

    int func() {
        return B::somethingStatic;
    }
};

class B {
public:
    static int somethingStatic;

    int func() {
        return A::somethingStatic;
    }
};

构建失败,因为 B 未定义。
那么我该如何解决呢?

【问题讨论】:

  • A::func的定义放在B的定义之后。您不必在类定义中编写成员函数。

标签: c++ class oop static circular-dependency


【解决方案1】:

您不能定义 A::func() 至少在声明 B 之前引用 B 的成员。B 的前向声明只是说将存在一个名为 B 的类,与 B 的成员无关。但是,您可以声明 A::func()

执行此操作的一种方法是典型的 .h 文件/.cpp 文件组合。如果您出于某种原因想要将所有 A 和 B(声明和定义)放在一个文件中,则可以按以下方式完成:

class A {
public:
    static int somethingStatic;

    int func();
};

class B {
public:
    static int somethingStatic;

    int func() {
        return A::somethingStatic;
    }
};

int A::func() {
    return B::somethingStatic;
}

int A::somethingStatic = 42;
int B::somethingStatic = 5;

请注意,在这种情况下,甚至不再需要转发声明 B,因为 A 的声明根本不依赖于 B。如果您将两者的定义分解为单独的 .cpp 文件,情况也是如此。

【讨论】:

    【解决方案2】:

    将成员函数的定义移出类声明

    // declarations go into a header file
    class A {
    public:
        static int somethingStatic;
        int func();
    };
    
    class B {
    public:
        static int somethingStatic;
        int func();
    };
    
    // definitions go into a cpp file
    int A::func() {
        return B::somethingStatic;
    }
    
    int B::func() {
        return A::somethingStatic;
    }
    
    // don't forget to define static member variables:
    int A::somethingStatic;
    int B::somethingStatic;
    

    分离声明和定义应该是您的“默认操作模式”,因为从标头中删除实现会使您的代码更易于导航。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-24
      相关资源
      最近更新 更多