【问题标题】:What will this print out and why? How would you fix it? [C++]这将打印出什么,为什么?你会如何解决它? [C++]
【发布时间】:2017-06-24 23:20:40
【问题描述】:

以下打印出来

0 2

应该打印出来

1 2

我尝试逐行遍历,并在 UtilsA.cpp 通过其 GetNumber() 函数返回 0 处结束。它与 UtilsC.cpp 完全相同,并返回正确的数字。我该怎么做才能解决这个问题?为什么会这样?

UtilsA.h

namespace UtilsA {
    int GetSingleNumber();
}

UtilsA.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();
}

UtilsB.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();
}

UtilsC.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;
}

【问题讨论】:

标签: c++ class header


【解决方案1】:

我很好奇,因为我不明白问题的原因,但是所有的学分应该去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 做同样的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 2021-12-08
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多