【发布时间】:2010-12-09 10:25:41
【问题描述】:
我想知道为什么有时我在单独的 .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;
}
class.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
class.cpp
#include "class.h"
A::A()
: a(CONST){}
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 类却没有?
【问题讨论】:
标签: c++ constructor constants