如何将变量存储为空

时间:2019-12-30 02:20:18

标签: 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。

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

我该怎么办?

1 个答案:

答案 0 :(得分:3)

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';
}