【发布时间】:2016-02-28 01:13:07
【问题描述】:
假设我有两个不同版本的同一个标头foo.hpp,第一个:
// File foo.hpp
#ifndef FILE_FOO
#define FILE_FOO
namespace X
{
static const int i = 13;
static const double d = 17.0;
}
#endif
第二个:
// File foo.hpp
#ifndef FILE_FOO
#define FILE_FOO
struct X
{
static const int i = 13;
static const double d = 17.0;
};
#endif
在后一种情况下,使用结构是没有意义的,但我故意这样做是为了突出我的问题。在这两种情况下,我都尝试构建以下源文件foo.cpp:
// File foo.cpp
#include "foo.hpp"
#include <iostream>
int main()
{
std::cout << X::i << std::endl;
std::cout << X::d << std::endl;
return 0;
}
但仅在后者中我收到以下错误:
In file included from foo.cpp:2:
foo.hpp:7: error: floating-point literal cannot appear in a constant-expression
foo.hpp:7: error: ISO C++ forbids initialization of member constant ‘d’ of non-integral type ‘const double’
我正在使用g++ 4.2.1(所以仍然使用C++98标准)和-pedantic,这个选项是严格要求得到上述错误的。
正如here 所讨论的,我可以看到只允许在类中初始化静态常量整数或枚举类型的点,因为我猜 C++ 标准没有指定在编译时应该如何实现浮点,它把它留给处理器。但在这一点上,命名空间案例误导了我......
最后,问题:
- 在上述两种情况下,编译器如何将源代码翻译成目标代码?
- 为什么只有第二个版本的标头才会报错?
感谢您的帮助!
【问题讨论】:
标签: static compilation initialization g++ constants