c++ - 如何将变量存储为空

标签 c++

我有一个带有unsigned chars的类。

有该类的第一个实例:

{
    unsigned char a = 5;
    unsigned char b = 243;
    unsigned char c = 0;
}

但是有一种选择,其中一些unsigned chars不会被填充。

实例如下所示:
{
    unsigned char a = 4;
    unsigned char b = 7;
    unsigned char c = <not_filled>;
}

我知道有一个NULL定义为零,所以我无法确定它是否为零或not_filled。

我知道如果我保持变量未定义,它将为零。

我该怎么办?

最佳答案

std::optional是您的所需内容:

#include <optional>

struct MyStruct {
    std::optional<unsigned char> a = 4;
    std::optional<unsigned char> b = 7;
    std::optional<unsigned char> c = std::nullopt;
};

用法示例:
#include <iostream>
#include <optional>

struct MyStruct {
    std::optional<unsigned char> a = std::nullopt;
    std::optional<unsigned char> b = std::nullopt;
    std::optional<unsigned char> c = std::nullopt;
};

int main() {
    MyStruct ms{'a', 'b'};
    if (ms.a.has_value()) std::cout << *ms.a << '\n';
    if (ms.b.has_value()) std::cout << *ms.b << '\n';
    if (ms.c.has_value()) std::cout << *ms.c << '\n';
}

关于c++ - 如何将变量存储为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59525004/

相关文章:

c++ - 是否可以删除此条件语句?

c++ - 双重免费或损坏 : C++

c++ - 除以零后无运行时错误

c++ - 如何在 Linux 上以编程方式 (C/C++) 获取国家/地区代码?

c++ - 超时错误 C++

c++ - 在Linux ubuntu中用c++调用具有两个输出的函数时出错

c++ - 非法引用非静态成员...typedef?

c++ - 在 C++ 中重写转换操作

c++ - VS2015 没有链接 user32.lib

c++ - 尝试使用 Qt 库中的 QPixmap 将图像分成几个 block 。他的复制方法的工作方式有什么我不明白的吗?