阿拉尔市网站建设_网站建设公司_响应式开发_seo优化
2025/12/28 16:38:14 网站建设 项目流程

Optional

Optional: 三种处理可能存在,可能不存在的数据的方式之一

#include<iostream>
#include<string>
#include<fstream>
#include<optional>std::string ReadFileAsString(const std::string& filePath, bool& outSuccess) {std::ifstream stream(filePath);if (stream) {//read filestd::string result;stream.close();return result;}return std::string();
}std::optional<std::string> ReadFileAsStringOptional(const std::string& filePath) {std::ifstream stream(filePath);if (stream) {//read filestd::string result;stream.close();return result;}return {};
}int testReadFileAsStringOptional() {bool outSuccess;std::string data = ReadFileAsString("data.txt", outSuccess);//判断方式一,返回结果if (data != "") {}//判断方式二,外部值传递if (outSuccess) {}//判断方式三,Optionalstd::optional<std::string> data2 = ReadFileAsStringOptional("data.txt");if (data2.has_value()) {std::cout << "File read successfully. data: " << data2.value() << "\n";std::cout << "File read successfully. data: " << data2.value_or("hello world") << "\n";} else {std::cout << "File couldn't be opened.\n";}//因为data2对象有一个bool运算符,所以不用谢has_valueif (data2) {}std::optional<int> count;int c = count.value_or(100);
}int main() {testReadFileAsStringOptional();std::cin.get();
}

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询