struct带有布尔字段默认初始化? [英] Struct with boolean field default initialization?

查看:506
本文介绍了struct带有布尔字段默认初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下用例,一个带有一些布尔和整数变量的结构。

I have the following use case, a struct with some boolean and int variables

struct a {

    int field1;
    bool field2;
    bool field3;

};

我重构这个代码,并为结构写一个构造函数,问题是默认初始化字段。

I am refactoring this code, and writing a constructor for the struct , the problem is the default initialization of fields.

我不是在这里批评任何语言结构,但理想情况下,我希望null成为语言本身的一部分

I am not criticizing any language construct here, but ideally I would want null to be part of the language itself

我的意思是我应该能够定义结构a为

i mean I should be able to define for struct a as

a : field1(null.int), field2(null.bool), field3(null.bool) {}

C ++不允许.int或null.bool未定义。是C ++中唯一的方法是

C++ does not allow it since null.int or null.bool are not defined. Is the only way to do in C++ is

a: field1(-1), field2(false), field3(false) {}


推荐答案


$ b

You can do

struct a {
    a():field1(), field2(), field3() { }
    int field1;
    bool field2;
    bool field3;
};

所有字段将分别为零和false。如果你想说字段有一个不确定的值,恐怕你必须使用其他技术。一种是使用 boost :: optional

And all fields will be zero and false respectively. If you want to say that the fields have an indeterminate value, i'm afraid you have to use other techniques. One is to use boost::optional:

struct a {
    a():field1(int()), field2(bool()) { }
    optional<int> field1;
    optional<bool> field2;
    optional<bool> field3;
};

叶子字段3不确定。使用 * field_name 访问值。用字段== boost :: none if(field){...} 测试无值。

Leaves field3 indeterminate. Access the values with *field_name. Test for a none value with field == boost::none or if(field) { ... }.

这篇关于struct带有布尔字段默认初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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