如何在使用g ++编译器时使用c样式初始化结构?

inj*_*joy 3 c c++ struct fuse

通常,为了初始化structin c,我们只能指定部分字段.如下所示:

static struct fuse_operations hello_oper = {
    .getattr    = hello_getattr,
    .readdir    = hello_readdir,
    .open       = hello_open,
    .read       = hello_read,
};
Run Code Online (Sandbox Code Playgroud)

但是,在C++中,我们应该在struct没有命名字段的情况下初始化变量.现在,如果我想struct在使用g ++编译器时使用c样式初始化,如何实现呢?PS:我需要这样做的原因是它struct fuse_operations有太多的字段.

Don*_*ner 5

你写了:

   static struct fuse_operations hello_oper = {
       .getattr    = hello_getattr,
       .readdir    = hello_readdir,
       .open       = hello_open,
       .read       = hello_read,
   };
Run Code Online (Sandbox Code Playgroud)

通常,为了在c中初始化结构,我们只能指定部分字段[...]但是,在C++中,我们应该初始化结构中的变量而不命名字段.现在,如果我想在使用g ++编译器时使用c样式初始化结构,怎么做呢?PS:我需要这样做的原因是struct fuse_operations中包含太多字段.

我的解决方案是使用构造函数来专门化struct:

struct hello_fuse_operations:fuse_operations
{
    hello_fuse_operations ()
    {
        getattr    = hello_getattr;
        readdir    = hello_readdir;
        open       = hello_open;
        read       = hello_read;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后声明新结构的静态实例:

static struct hello_fuse_operations hello_oper;
Run Code Online (Sandbox Code Playgroud)

测试对我来说没问题(但这取决于C-struct和C++的内存布局 - 结构是一样的 - 不确定是否有保证)

*更新*

虽然这种方法在实践中运行良好,但我随后将我的代码转换为使用实用程序类,即具有单个静态"初始化"方法的类,该方法引用fuse_operation结构并初始化它.这避免了有关内存布局的任何可能的不确定性,并且通常是我推荐的方法.


das*_*ght 3

不幸的是,即使是 C++ 标准的 C++11 版本也缺少 C99 的指定初始值设定项功能