考虑以下。我有两个导出常量,如下所示:
// somefile.h
extern const double cMyConstDouble;
extern const double cMyConstDouble2;
and
// somefile.cpp
const double cMyConstDouble = 3.14;
const double cMyConstDouble2 = 2.5*cMyConstDouble;
现在在其他地方引用这些常量来定义两个静态(本地可见)常量:
// 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);
产生以下输出:
cAnotherDouble = 3.454, cAnotherDouble2 = 0
为什么第二个是双0?我正在使用 .NET 2003 C++ 编译器 (13.10.3077)。
我不打算在这里深入探讨 extern 的问题,但是为什么您不将 const 放在适当的头文件中,而忘记使用 extern“导出”它们呢?这就是 const 在 C++ 中的使用方式,以及它们具有内部链接的原因。
换句话说:
// someheader.h
const double cMyConstDouble = 3.14;
const double cMyConstDouble2 = 2.5*cMyConstDouble;
并在需要的地方 #include 该文件。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)