简体   繁体   English

C++ Class 未初始化

[英]C++ Class is not being Initialized

In C++ you can't include Header Files in each other because of recursion.在 C++ 中,由于递归,您不能在彼此中包含 Header 文件。 So you have to make use of Predefined Classes right?所以你必须使用预定义类对吗? So I want to get the value of num in C.hpp and print it out in B.hpp .所以我想在 C.hpp 中获取num 的值并在 B.hpp 中打印出来

C Class gets initialized before B Class which is expected. C Class 在 B Class 之前被初始化,这是预期的。

Console Output控制台 Output

But when I'm trying to call A::instance->c it is NULL !但是当我尝试调用 A::instance->c 时,它是NULL

B Class with unitialized C Class B Class 与单元化 C Class

A.hpp 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 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 C.hpp

class C {
public:
    int num = 0;

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

Source.cpp源.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 之前被初始化,这是预期的。

No, it's not expected, the order of evaluation of function arguments is unspecified.不,这不是预期的,function arguments 的评估顺序未指定。

But even if that's the case as in your example output, you've created new C class object, and now you are trying to create B class object and during that, you are trying to access A::instance->c which is not set yet . But even if that's the case as in your example output, you've created new C class object, and now you are trying to create B class object and during that, you are trying to access A::instance->c which is not设置呢

You set c for class A object in the start function, but you are still evaluating its parameters during this calls and didn't reach the actual body of the function. You set c for class A object in the start function, but you are still evaluating its parameters during this calls and didn't reach the actual body of the function.

Thus, the c in the class A is the default 0 as you set by C* c{ 0 };因此, c A 中的 c 是您通过C* c{ 0 }; . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM