这篇文章写的很好,下半部分还未完全理解,后续还需要回头来看看20190706():
https://www.cnblogs.com/likaiming/p/9045642.html
简单实践如下:
#include <iostream> using namespace std; int getI(){ return 1; } int main(){ cout << "左值引用实践:" << endl; int a = 1; int &r=a; cout << "a:" << a << endl; cout << "r:" << r << endl; a = 11; cout << "a:" << a << endl; cout << "r:" << r << endl; r = 22; cout << "a:" << a << endl; cout << "r:" << r << endl; cout << "左值引用实践end.\n\n\n" << endl; cout << "右值引用实践:" << endl; int a1 = getI(); int &r1=a1; cout << "a1:" << a1 << endl; cout << "r1:" << r1 << endl; // 这样使用错误 原因是getI()返回值是临时变量,没有一个变量指向他, // 这种情况要使用右值引用&& //int &r2=getI(); int &&r2=getI(); cout << "r2:" << r2 << endl; cout << "end." << endl; return 0; }
输出: