一般来说,为了初始化一个struct
在c中,我们只能指定部分字段。就像下面这样:
static struct fuse_operations hello_oper = {
.getattr = hello_getattr,
.readdir = hello_readdir,
.open = hello_open,
.read = hello_read,
};
然而,在C++中,我们应该初始化变量struct
而不命名字段。
现在,如果我想初始化一个struct
使用c风格同时使用g++编译器,如何实现这一点? PS:我需要这样做的原因是struct fuse_operations
其中有太多字段。
你写了:
static struct fuse_operations hello_oper = {
.getattr = hello_getattr,
.readdir = hello_readdir,
.open = hello_open,
.read = hello_read,
};
一般来说,为了在c中初始化一个结构体,我们只能指定部分字段[...]但是,在C++中,
我们应该初始化结构中的变量而不命名字段。现在,如果我想初始化怎么办
使用 c 风格的结构体,同时使用 g++ 编译器,如何实现这一点? PS:我需要这样做的原因
是结构体fuse_operations中有太多字段。
我的解决方案是使用构造函数来专门化结构:
struct hello_fuse_operations:fuse_operations
{
hello_fuse_operations ()
{
getattr = hello_getattr;
readdir = hello_readdir;
open = hello_open;
read = hello_read;
}
}
然后声明新结构的静态实例:
static struct hello_fuse_operations hello_oper;
测试对我来说没问题(但这取决于 C 结构和 C++ 结构的内存布局是否相同——不确定是否能保证)
* 更新 *
尽管这种方法在实践中效果很好,但我随后将代码转换为使用实用程序类,即具有单个静态“初始化”方法的类,该方法引用fuse_operation结构并对其进行初始化。这避免了有关内存布局的任何可能的不确定性,并且通常是我推荐的方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)