我在这个链接中找到了上面的代码,它告诉这个例子 std::option 非常适合!
class UserRecord
{
public:
UserRecord(const std::string& name, std::optional<std::string> nick, std::optional<int> age)
: mName{ name }, mNick{ nick }, mAge{ age }
{
}
friend std::ostream& operator << (std::ostream& stream, const UserRecord& user);
private:
std::string mName;
std::optional<std::string> mNick;
std::optional<int> mAge;
};
std::ostream& operator << (std::ostream& os, const UserRecord& user)
{
os << user.mName << ' ';
if (user.mNick) {
os << *user.mNick << ' ';
}
if (user.mAge)
os << "age of " << *user.mAge;
return os;
}
int main()
{
UserRecord tim{ "Tim", "SuperTim", 16 };
UserRecord nano{ "Nathan", std::nullopt, std::nullopt };
std::cout << tim << "\n";
std::cout << nano << "\n";
}
我在下面创建了另一个没有可选的,我发现它比使用std::option
.
我认为第二个版本更具可读性,因为不需要使用std::nullopt
class UserRecord
{
public:
UserRecord(const std::string& name, std::string nick = "", int age = 0)
: mName{ name }, mNick{ nick }, mAge{ age }
{
}
friend std::ostream& operator << (std::ostream& stream, const UserRecord& user);
private:
std::string mName;
std::string mNick;
int mAge;
};
std::ostream& operator << (std::ostream& os, const UserRecord& user)
{
os << user.mName << ' ';
if (user.mNick != "") {
os << user.mNick << ' ';
}
if (user.mAge != 0)
os << "age of " << user.mAge;
return os;
}
int main()
{
UserRecord tim{ "Tim", "SuperTim", 16 };
UserRecord nano{ "Nathan" };
std::cout << tim << "\n";
std::cout << nano << "\n";
}
那么,为什么我们需要在一般情况下特别是在这种情况下使用 optional 呢?