c++核心編程<引用>
- 2.引用
- 2.1引用的基本使用
- 2.2引用注意事項(xiàng)
- 2.3引用做函數(shù)參數(shù)
- 2.4引用做函數(shù)返回值
- 2.5引用的本質(zhì)
- 2.6常量引用
2.引用
2.1引用的基本使用
2.2引用注意事項(xiàng)
- 引用必須初始化
- 引用在初始化后,不可以改變
- 無論是操作別名,還是操作原名,都是操作同一塊內(nèi)存
#include<iostream>
using namespace std;int main()
{int num1 = 12;int num2 = 25;int &num = num1; num = num2; cout << num << endl; cout << num1 << endl; cout << num2 << endl; system("pause");return 0;
}
2.3引用做函數(shù)參數(shù)
- 函數(shù)傳參時(shí),可以利用引用的技術(shù)讓形參修飾實(shí)參
- 可以簡化指針修改實(shí)參
#include<iostream>
using namespace std;
void SwapNum(int a, int b);
void SwapAdd(int* a, int* b);
void SwapRef(int& a, int& b);int main() {int a = 10;int b = 20;SwapNum(a, b);cout << "a = " << a << endl;cout << "b = " << b << endl;SwapAdd(&a, &b);cout << "a = " << a << endl;cout << "b = " << b << endl;SwapRef(a, b);cout << "a = " << a << endl;cout << "b = " << b << endl;system("pause");return 0;
}void SwapNum(int a, int b) {int temp = a;a = b;b = temp;
}
void SwapAdd(int* a, int* b) {int temp = *a;*a = *b;*b = temp;
}
void SwapRef(int& a, int& b) {int temp = a;a = b;b = temp;
}
2.4引用做函數(shù)返回值
- 引用是可以作為函數(shù)的返回值存在的
- 不要返回局部變量引用
- 函數(shù)調(diào)用為左值
#include<iostream>
using namespace std;
int& test_1();
int& test_2();int main() {int& ref = test_1();cout << "ref = " << ref << endl; cout << "ref = " << ref << endl;int& ref2 = test_2();cout << "ref2 = " << ref2 << endl; cout << "ref2 = " << ref2 << endl; cout << "ref2 = " << ref2 << endl; test_2() = 1000;cout << "ref2 = " << ref2 << endl; system("pause");return 0;
}int& test_1() {int a = 10;return a;
}int& test_2() {static int a = 10;return a;
}
2.5引用的本質(zhì)
- 本質(zhì): 引用的本質(zhì)在C++內(nèi)部實(shí)現(xiàn)是一個(gè)指針常量
#include<iostream>
using namespace std;
void func(int& ref);int main() {int a = 10;int& ref = a;ref = 20;cout << "a = " << a << endl; cout << "ref = " << ref << endl; func(a);cout << "ref = " << ref << endl; system("pause");return 0;
}void func(int& ref) {ref = 100;
}
2.6常量引用
- 作用: 常量引用主要用來修飾形參,防止誤操作
- 在函數(shù)形參列表中,可以加const修飾形參,防止形參改變實(shí)參
#include<iostream>
using namespace std;void showValue(int& value);int main() {int a = 10;int& ref = a;const int& ref2 = 10;int num = 1000;showValue(num);system("pause");return 0;
}
void showValue(int& value) {cout << "value = " << value << endl;
}
void showValue(const int& value) {cout << "value = " << value << endl;
}