您的位置:首页 > 其它

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

2013-05-16 11:05 99 查看
// 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语句决定而是由函数头部和函数原型决定

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: