返回值可接受为空,用以表示状态失败
举个栗子,
#include <iostream>
#include <optional>
using namespace std;
class User{
string name;
optional<string> nickName;
optional<int> age;
public:
User(const string& name,optional<string> nickName,optional<int> age):name(name),nickName(nickName),age(age){}
friend ostream& operator << (ostream& stream,const User& user);
};
ostream& operator << (ostream& os,const User& user) {
os<< user.name << ' ';
if(user.nickName) {
os<< *user.nickName << ' ';
}
if(user.age) {
os <<"age of" << *user.age;
}
return os;
}
int main() {
User peter("Peter", "Spiderman", 20);
User chris("Chris", nullopt, nullopt);
cout << peter << endl;
cout << chris << endl;
return 0;
}
Peter Spiderman age of20
Chris