引用就是对象的另一个名字,实际应用中引用主要用作函数的形式参数。
//正确 int ival = 1024; int &refcal = ival; //错误 int &refval; //错误原因:引用在定义的时候必须初始化 int &refval = 10;//错误原因:引用必须是一个变量(对象)引用是变量的别名,所以对引用进行操作时,实质是对引用的那个变量进行操作:
int ival = 1024; int &refval = ival; refval += 2; cout<< "refval=" << refval << endl; cout<< "ival=" << ival <<endl; //输出时ival也被加了2. #include <iostream> #include <vector> using namespace std; class VectorRef { //定义类变量 std::vector<int> vecInts; public: //构造函数 //初始化压入向量容器0~4 VectorRef(int size = 5) { for(int i =0; i< size; i++) vecInts.push_back(i); } //将类变量vecInts以引用的形式返回 std::vector<int> &GetVecInts() { return vecInts; } }; //将引用作为函数参数 void PrintVecInts (const std::vector<int> & vecInts) { printf("\n"); for(int i = 0; i< vecInts.size(); i++) printf("%d current value = %d\n",i,vecInts[i]); } void TestVecInts() { //定义一个类,此时自动调用了构造函数,已经填充了数字 VectorRef vRef; //返回引用,不会发生拷贝构造,v和vRef是同一个东西,如图1 vector<int>& v = vRef.GetVecInts(); //返回非引用,会发生拷贝构造,就是v变量vRef是不会变的,如图2 vector<int> v = vRef.GetVecInts(); v[0] = 100; PrintVecInts(v); PrintVecInts(vRef.GetVecInts()); } int main() { TestVecInts(); //getchar(); return 0; }