通常,为了初始化struct
in 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
有太多的字段.
你写了:
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结构并初始化它.这避免了有关内存布局的任何可能的不确定性,并且通常是我推荐的方法.
归档时间: |
|
查看次数: |
4851 次 |
最近记录: |