gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:28:49 24 4
gpt4 key购买 nike

一般情况下,为了在c中初始化一个struct,我们只能指定部分字段。如下所示:

static struct fuse_operations hello_oper = {
.getattr = hello_getattr,
.readdir = hello_readdir,
.open = hello_open,
.read = hello_read,
};

但是,在C++中,我们应该在struct中初始化变量而不命名字段。现在,如果我想在使用 g++ 编译器的同时使用 c 样式初始化一个 struct 怎么办?如何实现? PS:我需要这样做的原因是 struct fuse_operations 中的字段太多。

最佳答案

你写道:

   static struct fuse_operations hello_oper = {
.getattr = hello_getattr,
.readdir = hello_readdir,
.open = hello_open,
.read = hello_read,
};

通常,为了在 c 中初始化一个结构,我们只能指定部分字段 [...] 但是,在 C++ 中, 我们应该在不命名字段的情况下初始化结构中的变量。现在,如果我想初始化怎么办 使用 g++ 编译器时使用 c 样式的结构,如何实现? PS:我需要这样做的原因 是 struct 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-struct 和 C++-struct 的内存布局是否相同——不确定是否有保证)

* 更新 *

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

关于c++ - 如何在使用 g++ 编译器时使用 c 样式初始化结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12122234/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com