gpt4 book ai didi

c++ - 如何在 C++ 中新建和初始化结构?

转载 作者:行者123 更新时间:2023-11-30 00:35:28 25 4
gpt4 key购买 nike

在 C 中,我们实际上是这样做的

struct node *p = (node*)malloc(sizeof(node));   // casting is not necessary
p->a = 0; // first element
p->b = NULL; // second element

在内存中动态分配空间,但我如何用 C++ 方式做到这一点?

下面的线是正确的猜测吗?

node *p = new node {0, NULL};

最佳答案

是的,你是对的。

假设 node 是一个聚合,your C++ version is right (取模 NULL 而不是 nullptr)。

也就是说,如果这些初始值是“默认值”,您通常会编写一个默认构造函数来自动为您初始化这些成员:

struct node
{
int a;
node* b;

node() : a(0), b(nullptr) {}
};

然后你只需要写:

node* p = new node;

或者,更好的是:

auto p = std::make_unique<node>();

或者,更好的是:

node n;

默认构造虽然有一些后果。您可能不需要任何构造函数。

关于c++ - 如何在 C++ 中新建和初始化结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29304846/

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