Gui*_*i13 6 c++ tags static struct initialization
我搜索了stackoverflow的答案,但我无法得到相关的东西.
我正在尝试通过指定其标记来初始化具有初始值的静态结构实例,但是在编译时遇到错误:
src/version.cpp:10: error: expected primary-expression before ‘.’ token
这是代码:
// h
typedef struct
{
int lots_of_ints;
/* ... lots of other members */
const char *build_date;
const char *build_version;
} infos;
Run Code Online (Sandbox Code Playgroud)
而错误的代码:
// 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;
}
Run Code Online (Sandbox Code Playgroud)
所以基本的想法是绕过"其他成员"的初始化,只设置相关build_date和build_version值.这曾经在C中工作,但我无法弄清楚为什么它在C++中不起作用.
有任何想法吗?
编辑:
我意识到这个代码看起来像简单的C,它实际上是.整个项目是用C++编写的,所以我必须使用C++文件扩展来防止makefile依赖混乱(%.o: %.cpp)
下面的示例代码在我认为更多的C++方式(不需要typedef)中定义了一个结构,并使用构造函数来解决您的问题:
#include <iostream>
#define VERSION_DATE "TODAY"
#define VERSION_REVISION "0.0.1a"
struct infos {
int lots_of_ints;
/* ... lots of other members */
const char *build_date;
const char *build_version;
infos() :
build_date(VERSION_DATE),
build_version(VERSION_REVISION)
{}
};
static const infos s_infos;
const infos *get_info()
{
return &s_infos;
}
int main() {
std::cout << get_info()->build_date << std::endl;
std::cout << get_info()->build_version << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)