c++++ 函数的返回码用于表示操作的结果,常见返回码含义包括:0:操作成功1:操作失败-1:内存分配失败-2:文件打开失败-3:参数不正确-4:资源不足-5:无效指针

在 C++ 中,函数通常通过返回值来传递信息。返回码是一个整数,表示函数操作的结果。
以下是一些常见的返回码含义:
| 返回码 | 含义 |
|---|---|
| 0 | 操作成功 |
| 1 | 操作失败 |
| -1 | 内存分配失败 |
| -2 | 文件打开失败 |
| -3 | 参数不正确 |
| -4 | 资源不足 |
| -5 | 无效指针 |
实战案例:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <fstream>
using namespace std;
// 自定义函数,打开文件并读取其第一行
int open_and_read_file(const char* filename) {
ifstream file(filename);
if (file.is_open()) {
string line;
getline(file, line);
cout << "读取文件成功,第一行:" << line << endl;
return 0; // 操作成功
} else {
cerr << "文件打开失败" << endl;
return -2; // 文件打开失败
}
}
int main() {
const char* filename = "test.txt";
int result = open_and_read_file(filename);
switch (result) {
case 0:
cout << "操作成功" << endl;
break;
case -2:
cout << "文件打开失败" << endl;
break;
default:
cout << "未知错误" << endl;
}
return 0;
}输出:
读取文件成功,第一行:这是一个测试文件 操作成功
在这个实战案例中,open_and_read_file() 函数返回 0,表示操作成功,因此主函数中的 switch 语句正确打印了 "操作成功" 消息。
以上就是C++ 函数返回值:速查常见的返回码含义的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号