c++引用筆記

<code>#include <iostream>
using namespace std;


int main(void)
{
//引用基本數據類型
// 數據類型 &別名 = 原名


int a=10;
//創建引用
int &b=a;

cout< cout< b=100;

cout< cout<

//1.引用必須要初始化
// int &b; //錯誤的
int a=10; //int &b; 錯誤的
int &b=a;
//2.引用一旦初始化,不可以發生改變
int c=20;
b=c; //賦值操作,而不是更改引用

cout< cout< cout<



system("pause");
return 0;

}


//////////////////////////////////////////////////
#include <iostream>
using namespace std;

//交換函數

//1.值傳遞
void mySwap01(int a,int b)
{
int temp=a;
a = b;
b = temp;


cout< cout<}

//2.地址傳遞
void mySwap02(int *a,int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}

//3.引用傳遞
void mySwap03(int &a,int &b)
{
int temp = a;
a = b;
b = temp;
}
int main(void)
{
int a=10;
int b=20;
//mySwap01(a,b);//值傳遞,形參不會修飾實參
//mySwap02(&a,&b);//地址傳遞,形參會修飾實參的
mySwap03(a,b); //引用傳遞,形參會修飾實參的
cout< cout<

system("pause");
return 0;
}
/////////////////////////////////////////////
#include <iostream>
using namespace std;

//引用做函數的返回值
//1.不要返回局部變量的引用

int & test01()
{
int a=10; //局部變量存放在四區中的棧區
return a;
}

//2.函數的調用可以作為左值
int & test02()
{
static int a=10;//靜態變量,存放在全局區,全局上的數據在程序結束後會系統釋放
return a;
}
int main(void)
{


//int &ref =test01();
//cout <
int &ref2 = test02(); //如果函數的返回值是引用,這個函數調用可以作為左值
cout < cout <
test02()=1000;
cout < cout <

system("pause");
return 0;
}
/////////////////////////////////////
#include <iostream>
using namespace std;

//引用的本質:引用的本質在c++內部實現是一個指針常量
//發現是引用,轉換為int * const ref = &a;
void func(int& ref)
{
ref = 100; //ref是引用,轉換為*ref = 100;
}

int main(void)
{
int a=10;

int& ref = a;
//自動轉換為int * const ref = &a;指針常量是指針指向不可更改,也說明為啥引用不可更改

ref = 20; //內部發現ref 是引用,自動幫我們轉換為:*ref = 20;

cout < cout <
func(a);
cout < cout <
system("pause");
return 0;

}
////////////////////////
//引用使用的場景,通常用來修飾形參
void showValue(const int& v) {
//v += 10;
cout << v << endl;
}

int main() {

//int& ref = 10; 引用本身需要一個合法的內存空間,因此這行錯誤
//加入const就可以了,編譯器優化代碼,int temp = 10; const int& ref = temp;
const int& ref = 10;

//ref = 100; //加入const後不可以修改變量
cout << ref << endl;

//函數中利用常量引用防止誤操作修改實參
int a = 10;
showValue(a);

system("pause");

return 0;
}/<iostream>/<iostream>/<iostream>/<iostream>/<code>


分享到:


相關文章: