# return 语句有两种形式:
* return;
* return 值;
# 函数的返回:
1.主函数返回值,返回即结束,我们获取不到(应该是给返回系统的吧)
2.反馈非引用类型
3.返回引用
4.一定不要返回局部对象的引用(或者指针)
5.返回引用是一个左值,可以对其修改
Demo1:
#include <iostream>
using namespace std;
/*return语句*/
/// 1.返回值
int add(int a, int b)
{
return a+b;
}
/// 2.结束程序
void swap(int &a, int &b)
{
cout << "\n\n两值交换:\n";
if (a == b){
cout << "两个变量值相等.\n";
return; //提前结束,节省时间
}
int temp = a;
a = b;
b = temp;
return; //可以省略
}
int main()
{
int num1 = 77, num2 = 22;
//返回值
cout << "返回值:" << add(num1, num2) << endl;
//不同变量交换
swap(num1, num2);
cout << "num1 = " << num1 << endl;
cout << "num2 = " << num2 << endl;
//同一个变量交换
swap(num1, num1);
return 0;
}
输出:Demo2:
#include <iostream>
using namespace std;
/*return_语句*/
/// 不改变a的值
int add_1(int x)
{
++x;
return x; //把x复制一份,返回
}
/// 改变a的值, 返回也是引用
int& add_2(int &x)
{
++x;
return x; //返回的就是x自身
}
int main()
{
int a =0, b = 0;
a = 100;
b = add_1(a);
cout << "add_1: "
<< "a = " << a << ", "
<< "b = " << b << endl << endl;
int &c = add_2(a);
++c; //返回的是引用,c和a是一样的,改变c即改变了a
cout << "add_2: "
<< "a = " << a << ", "
<< "c = " << c << endl << endl;
/// 引用类型的返回值是一个左值,可以被修改
add_2(a) = 88;
cout << "引用类型的返回值是一个左值: " << a << endl;
return 0;
}
输出:
Demo3:
#include <iostream>
#include <string>
using namespace std;
/*return返回应用*/
// 使用了const修饰,作为常引用,不改变原来的变量,又不会浪费内存
const string& shorter(const string &str1, const string &str2)
{
return str1.size() < str2.size() ? str1 : str2;
}
/// 注意:不要返回局部对象(也不要返回局部的指针)
/// 编译可以通过,运行时会出错
const string& return_err(void)
{
string ret = "Hello";
return ret; //返回ret,但它是局部对象,函数结束后,ret就不存在了,直接报错
}
int main()
{
const string ret = shorter("Ni hao", "Hello");
cout << "shorter is : " << ret << endl;
return 0;
}
输出: