C++学习笔记(四十三):c++ optional

本节介绍的是c++17中另一个新特性optional,用来处理可能存在也可能不存在的数据。接下来通过代码来展示该新特性。

  • 接下来通过代码展示为什么需要optional这个新特性
  • #include 
    #include 
    #include 
    
    //读取文件中的内容通过字符串的形式返回
    std::string ReadFileAsString(const std::string& filename)
    {
    	//一般的做法如下
    	std::ifstream stream(filename);
    	if (stream)
    	{
    		//read file
    		stream.close();
    		std::string result;  //假想result就是我们从文件中读到的字符串
    		return result;
    	}
    	return std::string();  //如果打开文件失败,则返回一个空字符串,但这样存在一个问题,如果文件本身就是空的,
    	                       //返回的也是空字符串,这样我们就不能确定是打开文件失败导致还是文件本身是空导致
    
    }
    
    int main()
    {
    	
    
    	std::cin.get();
    }
  • 使用optional新特性后的代码如下: 

  • #include 
    #include 
    #include 
    #include 
    
    //读取文件中的内容通过字符串的形式返回
    std::optional ReadFileAsString(const std::string& filename)
    {
    	//一般的做法如下
    	std::ifstream stream(filename);
    	if (stream)
    	{
    		//read file
    		stream.close();
    		std::string result;  //假想result就是我们从文件中读到的字符串
    		return result;
    	}
    	return {};  //如果打开文件失败,则返回一个空字符串,但这样存在一个问题,如果文件本身就是空的,
    	                       //返回的也是空字符串,这样我们就不能确定是打开文件失败导致还是文件本身是空导致
    
    }
    
    int main()
    {
    	std::optional date = ReadFileAsString("D:\date.txt");//这个文件是空文件,里面没有任何内容
    	if (date.has_value())
    	{
    		std::cout << "打开文件成功" << std::endl;
    	}
    	else
    	{
    		std::cout << "打开文件失败" << std::endl;
    	}
    
    	std::cin.get();
    }

    上述程序返回结果是“打开文件成功”,data.value()返回的是空字符串。

你可能感兴趣的:(学习,笔记)