c++ - 这将打印出什么,为什么?你会怎么修? [C++]

标签 c++ class header

打印出如下内容

0 2

它应该打印出来

1 2

我尝试逐行查看,直到 UtilsA.cpp 通过其 GetNumber() 函数返回 0 时结束。它与 UtilsC.cpp 完全相同,并且返回正确的数字。我能做些什么来解决这个问题,为什么会这样?

实用程序.h

namespace UtilsA {
    int GetSingleNumber();
}

实用程序.cpp

#include "UtilsA.h"

namespace {
    class A {
    public:
        int GetNumber() const { return Number; }
    private:
        int Number = 1;
    };
    A SingleNumberA;
}

int UtilsA::GetSingleNumber() {
    return SingleNumberA.GetNumber();
}

实用程序B.h

namespace UtilsB {
    int GetSingleNumberA();
    int GetSingleNumberC();
}

UtilsB.cpp

#include "UtilsB.h"
#include "UtilsA.h"
#include "UtilsC.h"

namespace {
    class B {
    public:
        B() : NumberA( UtilsA::GetSingleNumber() ), NumberC( UtilsC::GetSingleNumber() )  {}
        int GetNumberA() const { return NumberA; }
        int GetNumberC() const { return NumberC; }
    private:
        int NumberA;
        int NumberC;
    };
    B SingleNumberB;
}

int UtilsB::GetSingleNumberA() {
    return SingleNumberB.GetNumberA();
}

int UtilsB::GetSingleNumberC() {
    return SingleNumberB.GetNumberC();
}

实用程序.h

namespace UtilsC {
    int GetSingleNumber();
}

UtilsC.cpp

#include "UtilsC.h"

namespace {
    class C {
    public:
        int GetNumber() const { return Number; }
    private:
        int Number = 2;
    };
    C SingleNumberC;
}

int UtilsC::GetSingleNumber() {
    return SingleNumberC.GetNumber();
}

main.cpp

#include <iostream>
#include "UtilsB.h"

int main() {
    std::cout << UtilsB::GetSingleNumberA() << " " 
    << UtilsB::GetSingleNumberC() << std::endl;
}

最佳答案

我很好奇,因为我不明白问题的原因,但所有学分都应该转到 drescherjm ,我只是在这里确认他的回答。

问题可以从代码中重现并按照 isocpp.org/wiki/faq/ctors#static-init-order-on-first-use 中的说明进行操作它可以解决。将 UtilsC.h 替换为:

namespace {
    class C {
    public:
        int GetNumber() const { return Number; }
    private:
        int Number = 2;
    };
    C& SingleNumberC() {
        static C* ans = new C();
        return *ans;
    }
}

int UtilsC::GetSingleNumber() {
    return SingleNumberC().GetNumber();
}

并为 UtilsB.h 做同样的事情,而不是它应该工作的。

关于c++ - 这将打印出什么,为什么?你会怎么修? [C++],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44741818/

相关文章:

.net - 在循环中构建 IEnumerable

c++ - 如何在 C++ 中引用类结构中的函数?

php - 是否有一个 call_user_func() 相当于创建一个新的类实例?

c - 无法在头文件中找到结构体

C++:在另一种方法中使用预先声明的运算符[]

c++ - 使用 std::equal 和命名空间时出现 "No match operator=="错误

c++ - 将类型声明为类型模板参数的模板参数的一部分是否合法?

c++ - 类模板中没有对 T::T() 的匹配函数调用

c - 如何在 C 中链接多个实现文件

css - 滚动体*在*下方*一个透明的标题 div?