c++ - .h 或 .cpp 文件中的全局常量初始化和构造函数之间的区别

标签 c++ constructor constants

我想知道为什么有时我在单独的 .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/

相关文章:

c++ - 使用 Objective-C 获取 Photoshop 的 Action 列表

c++ - 算术右移给出虚假结果?

java - Java中的 "this"如何转义构造函数?

arrays - Delphi:const 对象的 const 列表

java - Java 中 "public static final"常量的 Clojure 等价物是什么

c++ - QTableview搜索

java - 有人可以解释 Java 中的构造函数吗?

c++ - 多个构造函数的内存使用c++

C 中的 Const 返回类型

c++ - 函数指针比内联函数运行得更快。为什么?