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

//Inventory Pointer
// Demonstrates returning a pointer




#include <iostream>
#include <string>
#include <vector>
using namespace std;
//returns a pointer to a string element
string* ptrToElement(vector<string>* const pVec, int i);


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




//displays string object that the returned pointer points to
cout << "Sending the objected pointed to by returned pointer:\n";       
cout << *(ptrToElement(&inventory, 0)) << "\n\n"; //调用ptrToElement(),返回指向inventory[0]的指针(不是元素的副本,而是指向元素的指针),然后将指针指向的string对
//象发送给cout,显示出sword




//assigns one pointer to another -- inexpensive assignment
cout << "Assigning the returned pointer to another pointer.\n";
string* pStr = ptrToElement(&inventory, 1); //将返回的指针赋值给指针,高效率
cout << "Sending the object pointed to by new pointer to cout:\n";
cout << *pStr << "\n\n";


//copies a string object -- expensive assignment
cout << "Assigning object pointed by pointer to a string object.\n";
string str = *(ptrToElement(&inventory, 2));  //将返回的指针指向的值赋值给变量,有开销
cout << "Sending the new string object to cout:\n";
cout << str << "\n\n";


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


return 0;
}




string* ptrToElement(vector<string>* const pVec, int i)      //函数头部的string*表示函数返回一个指向string对象的指针(而不是string对象本身)
{
//returns address of the string in position i of vector that pVec points to
return &((*pVec)[i]);  //逐层分解这个表达式。从内层开始,(*pVec)[i]的含义是pVec指向的向量中位置i处的元素。通过对该表达式应用取址运算符(&),表达式变成取其地址。
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值