如何在C ++ 11中将结构体中的指针初始化为null? [英] How do I initialize a pointer in a struct to null in C++11?

查看:827
本文介绍了如何在C ++ 11中将结构体中的指针初始化为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的结构:

struct node {
    int load;
    int tolerance;
    bool has_fired;
    node *in[1];
    node *out[1];
    };

我尝试过:

node mynode;

mynode->in = null;
mynode->in = nullptr;
mynode->in = &nullptr;
mynode->in = 0;
mynode->in = false;

我真的不知道出了什么问题,我记得第一个用于工作的任务,但显然已经不见了.有什么帮助吗?

I really don't know what's wrong, I remember the first assignment USED to work but not anymore apparently. Any help?

在实际的源文件中,"mynode"是另一个结构内部的指针.

In the actual source file 'mynode' is a pointer inside of another struct.

推荐答案

也许像这样:

struct node
{
    int load;
    int tolerance;
    bool has_fired;
    node *in[1] = { nullptr };
    node *out[1] = { nullptr };
};

(请注意,node::innode::out指针数组.)

用法:

node n;    // n.in and n.out are initialized

在C ++ 11中,括号或相等初始化器使该类成为非聚合类.如果有问题,您也可以省略初始化程序,然后说:

In C++11 the brace-or-equal-initializer makes the class a non-aggregate. If that's a problem, you can also omit the initializer and say:

node n;
n.in[0] = nullptr;
n.out[0] = nullptr;

甚至:

node n { 0, 0, false,  { nullptr }, { nullptr } };

这篇关于如何在C ++ 11中将结构体中的指针初始化为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆