C++ Class 未被初始化

C++ Class is not being Initialized

在 C++ 中,由于递归的原因,您不能相互包含头文件。所以你必须使用预定义的 Classes 对吗?所以我想在C.hpp中获取num的值并在B.hpp.

中打印出来

C Class 在 B Class 之前初始化,这是预期的。

Console Output

但是当我尝试调用 A::instance->c 时,它是 NULL!

B Class with unitialized C Class

A.hpp

#include <iostream>
class C;                        // PREDEFINED CLASS
class B;                        // PREDEFINED CLASS
class A {
public:
    inline static A* instance;
    C* c{ 0 };
    B* b{ 0 };

    A() {
        instance = this;
    }

    void start(B* b,C* c) {
        this->c = c;
        this->b = b;
    }
};

B.hpp

#include "A.hpp"
#include "C.hpp"

class B {
public:

    void call() {
        if (A::instance->c)
            std::cout << "C Num: " << A::instance->c->num << "\n";
        else std::cout << "C Class is NULL!\n";
    }

    B() {
        std::cout << "B init!\n";
        call();
    }
};

C.hpp

class C {
public:
    int num = 0;

    C() {
        std::cout << "C init!\n";
        num = 69;
    }
};

Source.cpp

#include "A.hpp"
#include "B.hpp"
#include "C.hpp"

void main() {
    A a;
    a.start(new B(), new C());
}

C Class gets initialized before B Class which is expected.

不,这不是预期的,函数参数的计算顺序未指定。

但即使是您的示例输出中的情况,您已经创建了新的 C class 对象,现在您正在尝试创建 B class 对象,在此期间,您是试图访问 尚未设置的 A::instance->c

您在 start 函数中为 class 对象设置了 c,但您在调用期间仍在计算其参数,没有到达函数的实际主体.

因此,class A 中的 c 是您通过 C* c{ 0 }; 设置的默认值 0。