对指针、引用的理解(三)【引用】

// Inventory Referencer
// Demonstrates returning a reference


#include <iostream>
#include <string>
#include <vector>


using namespace std;


//returns a reference to a string
string& refToElement(vector<string>& inventory, int i); 


int main()
{
vector<string> inventory;
inventory.push_back("sword");
inventory.push_back("armor");
inventory.push_back("shield");


//displays string that the returned reference refers to 
cout << "Sending the returned reference to cout:\n";  //显示返回的引用的值 
cout << refToElement(inventory, 0) << "\n\n";//返回inventory中位置0的元素的引用,代码随后将引用发送给cout,所以显示sword


//assigns one reference to another -- inexpensive assignment 
cout << "Assigning the returned reference to another reference.\n";
string& rStr = refToElement(inventory, 1); //将返回的引用赋值给另一个引用。这行代码将inventory中位置1处的元素的引用赋值给rStr
cout << "Sending the new reference to cout:\n";
cout << rStr << "\n\n";


//copies a string object -- expensive assignment
cout << "Assigning the returned reference to a string object.\n";
string str = refToElement(inventory, 2);//将返回的引用赋值给变量。代码将返回的引用所指向的元素(inventory位置2处的元素)进行复制,然后将该string对象的新的副本赋值给对象str
cout << "Sending the new string object to cout:\n";
cout << str << "\n\n";


//altering the string object through a returned reference
cout << "Altering an object through a returned reference.\n";
rStr = "Healing Potion";//通过返回的引用修改对象
cout << "Sending the altered object to cout:\n";
cout << inventory[1] << endl;


return 0;
}


//returns a reference to a string
string& refToElement(vector<string>& vec, int i)//通过在string&中使用引用运算符,说明函数返回一个指向string对象的引用(不是string对象自身)
{
return vec[i];//返回向量中位置i处的引用。返回对象还是对象的引用不是由return语句决定而是由函数头部和函数原型决定
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值