// ============================================================================ // p1c03_29 — 3.10.1 引用基本用法 // 来源:川大 C++/LinuxC wiki「02.Qt方向」 // 说明:本文件由 gen_part1.py 合并页面中的教学片段而成。每个片段用 // // --- 原文片段 [pageId:blockIdx] --- 标注出处。 // 已做最小修正(笔误/平台移植),详见 docs/ERRATA.md。 // ============================================================================ #include using namespace std; // --- 原文片段 [58954439:28] 3.10.1 引用基本用法 --- //1. 认识引用 void test01(){ int a = 10; //给变量a取一个别名b int& b = a; cout << "a:" << a << endl; cout << "b:" << b << endl; cout << "------------" << endl; //操作b就相当于操作a本身 b = 100; cout << "a:" << a << endl; cout << "b:" << b << endl; cout << "------------" << endl; //一个变量可以有n个别名 int& c = a; c = 200; cout << "a:" << a << endl; cout << "b:" << b << endl; cout << "c:" << c << endl; cout << "------------" << endl; //a,b,c的地址都是相同的 cout << "a:" << &a << endl; cout << "b:" << &b << endl; cout << "c:" << &c << endl; } //2. 使用引用注意事项 void test02(){ //1) 引用必须初始化 //int& ref; //报错:必须初始化引用 //2) 引用一旦初始化,不能改变引用 int a = 10; int b = 20; int& ref = a; ref = b; //不能改变引用 //3) 不能对数组建立引用 int arr[10]; //int& ref3[10] = arr; } // --- main --- int main() { test01(); test02(); return 0; }