// ============================================================================ // p1c03_32 — 3.10.2 函数中的引用 // 来源:川大 C++/LinuxC wiki「02.Qt方向」 // 说明:本文件由 gen_part1.py 合并页面中的教学片段而成。每个片段用 // // --- 原文片段 [pageId:blockIdx] --- 标注出处。 // 已做最小修正(笔误/平台移植),详见 docs/ERRATA.md。 // ============================================================================ #include using namespace std; // --- 原文片段 [58954439:31] 3.10.2 函数中的引用 --- //返回局部变量引用 int& TestFun01(){ int a = 10; //局部变量 return a; } //返回静态变量引用 int& TestFunc02(){ static int a = 20; cout << "static int a : " << a << endl; return a; } int main(){ //不能返回局部变量的引用 int& ret01 = TestFun01(); //如果函数做左值,那么必须返回引用 TestFunc02(); TestFunc02() = 100; TestFunc02(); return EXIT_SUCCESS; } // --- main ---