我想知道为什么有时我在单独的 .h 文件中定义的全局常量在我需要时没有正确初始化。一些测试导致我无法理解的情况。我不知道如何解释它,所以这是代码:
main.cpp
#include <iostream>
#include "class.h"
using namespace std;
A a;
B b;
int main(int argc, char* argv[]){
A aa;
B bb;
cout<<a.a<<" "<<aa.a<<endl;
cout<<b.b<<" "<<bb.b<<endl;
return 0;
}
类.h
#ifndef CLASS_H
#define CLASS_H
#include "const.h"
class A {
public:
A();
float a;
};
class B {
public:
B():b(CONST){}
float b;
};
#endif
类.cpp
#include "class.h"
A::A()
: a(CONST){}
常量.h
#ifndef CONST_H
#define CONST_H
#include <limits>
using namespace std;
const float CONST = numeric_limits<float>::has_infinity ?
-numeric_limits<float>::infinity() :
-numeric_limits<float>::max();
#endif
运行上面的代码后我得到:
0 -1.#INF
-1.#INF -1.#INF
实际上我想得到 4 次 '-1.#INF'。 为什么会这样?如果 CONST 为 '1' 而不是上面的公式,它将完美地工作。
我可以通过创建静态 getConst() 方法来“修复”它:
static float getConst(){
static const float CONST = numeric_limits<float>::has_infinity ?
-numeric_limits<float>::infinity() :
-numeric_limits<float>::max();
return CONST;}
但它只是“感觉”不对。另一方面,我只需要上面的两个...但也许还有其他方法?
而且,最重要的是,为什么 B 类获得“正确的”CONST 而 A 类没有?
最佳答案
全局对象在不同翻译单元中的初始化顺序不保证。
请看一下这个 stackoverflow 问题:Static variables initialisation order
关于c++ - .h 或 .cpp 文件中的全局常量初始化和构造函数之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4397156/