# 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;
}
輸出: