ral*_*nja 2 c++ double initialization const extern
考虑以下.我有两个导出的常量如下:
// somefile.h
extern const double cMyConstDouble;
extern const double cMyConstDouble2;
Run Code Online (Sandbox Code Playgroud)
和
// somefile.cpp
const double cMyConstDouble = 3.14;
const double cMyConstDouble2 = 2.5*cMyConstDouble;
Run Code Online (Sandbox Code Playgroud)
现在引用这些常量来定义两个静态(局部可见)常量:
// someotherfile.cpp
#include "somefile.h"
static const double cAnotherDouble = 1.1*cMyConstDouble;
static const double cAnotherDouble2 = 1.1*cMyConstDouble2;
printf("cAnotherDouble = %g, cAnotherDouble2 = %g\n",
cAnotherDouble, cAnotherDouble2);
Run Code Online (Sandbox Code Playgroud)
产生以下输出:
cAnotherDouble = 3.454, cAnotherDouble2 = 0
Run Code Online (Sandbox Code Playgroud)
为什么第二双0?我正在使用.NET 2003 C++编译器(13.10.3077).
小智 9
我不打算在这里讨论extern的问题,但是为什么你不把consts放在适当的头文件中而忘记使用extern"导出"它们?这就是C++中应该使用的consts,以及为什么它们具有内部链接.
换一种说法:
// someheader.h
const double cMyConstDouble = 3.14;
const double cMyConstDouble2 = 2.5*cMyConstDouble;
Run Code Online (Sandbox Code Playgroud)
和#include该文件,无论你需要它们.