void和status区别
时间: 2024-05-13 15:14:15 浏览: 23
`void` 和 `status` 是两种不同的类型。
`void` 是一种特殊的类型,它表示“无类型”或“空类型”。在函数声明或定义中,如果函数的返回值类型是 `void`,那么该函数不返回任何值。例如:
```c++
void printHello() {
std::cout << "Hello, world!" << std::endl;
}
```
`printHello` 函数的返回值类型是 `void`,因此它不返回任何值。
`status` 则是一种自定义类型,它通常用于表示函数执行的状态。在函数执行过程中,如果遇到错误或异常情况,函数可以返回一个 `status` 对象来表示执行失败的原因。例如:
```c++
enum class StatusCode {
OK,
InvalidArgument,
NotFound,
InternalError,
...
};
class Status {
public:
Status(StatusCode code, const std::string& message)
: code_(code), message_(message) {}
StatusCode code() const { return code_; }
std::string message() const { return message_; }
private:
StatusCode code_;
std::string message_;
};
Status readFile(const std::string& filename, std::string* content) {
// 打开文件
std::ifstream file(filename);
if (!file.is_open()) {
return Status(StatusCode::NotFound, "File not found");
}
// 读取文件内容
std::stringstream buffer;
buffer << file.rdbuf();
*content = buffer.str();
// 关闭文件
file.close();
return Status(StatusCode::OK, "OK");
}
```
`readFile` 函数的返回值类型是 `Status`,它表示函数执行的状态。如果函数执行成功,返回一个 `Status` 对象,其状态码为 `OK`,否则返回一个状态码和错误信息。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)