我已经在 stackoverflow 上搜索了一个答案,但我找不到相关的东西。
我正在尝试通过指定标签来初始化具有初始值的静态结构实例,但在编译时出现错误:
src/version.cpp:10: error: expected primary-expression before ‘.’ 标记
代码如下:
// h
typedef struct
{
int lots_of_ints;
/* ... lots of other members */
const char *build_date;
const char *build_version;
} infos;
错误代码:
// C
static const char *version_date = VERSION_DATE;
static const char *version_rev = VERSION_REVISION;
static const infos s_infos =
{
.build_date = version_date, // why is this wrong? it works in C!
.build_version = version_rev
};
const infos *get_info()
{
return &s_infos;
}
所以基本思路是绕过“其他成员”初始化,只设置相关的build_date
和build_version
值。
这曾经在 C 中工作,但我不明白为什么它在 C++ 中不起作用。
有什么想法吗?
编辑:
我意识到这段代码看起来像简单的 C,而实际上确实如此。整个项目都在 C++ 中,所以我必须使用 C++ 文件扩展名来防止 makefile 依赖困惑(%.o: %.cpp
)
最佳答案
您使用的功能是 C99 功能,而您使用的 C++ 编译器不支持它。请记住,虽然 C 代码通常是有效的 C++ 代码,但 C99 代码并不总是有效。
关于c++ - 在 C++ 中使用标记进行静态结构初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5790534/