c++ reference bind to object后,为什么这个绑定关系不能修改?

风划雪月 2014-11-25 01:45:15
#include <iostream>
class test
{
public:
test(int &v1,int &v2,int &v3):if1(v1),if2(v2),if3(v3){}
void show()
{
std::cout << if1 << std::endl;
std::cout << if2 << std::endl;
std::cout << if3 << std::endl;
return;
}
private:
int &if1;
int &if2;
int &if3;
};


int main()
{
int ia = 0;
int ib = 1;
int ic = 2;

/*reference itself store some thing in memory*/
std::cout << "sizeof test class\n";
std::cout << sizeof(test) << std::endl;

std::cout << "address of ia: ";
std::cout << &ia << std::endl;
/*print object's address*/
test ta(ia,ia,ia);
std::cout << "address of ia: ";
std::cout << static_cast<void *>(&ta) << std::endl;
/*print the reference context,this just the addres of object to which this reference bind*/
std::cout << "object real content\n";
std::cout << *static_cast<void **>(static_cast<void *>(&ta)) << std::endl;
std::cout << *(static_cast<void **>(static_cast<void *>(&ta)) + 1)<< std::endl;
std::cout << *(static_cast<void **>(static_cast<void *>(&ta)) + 2) << std::endl;

std::cout << "before change the reference bind to\n";
ta.show();
/*change reference itself's content*/
*(static_cast<void **>(static_cast<void *>(&ta)) + 1) = (void *)&ib;
*(static_cast<void **>(static_cast<void *>(&ta)) + 2) = (void *)⁣
std::cout << "after change the reference bind to\n";
ta.show();
return 0;
}

上面的程序说明reference自身的内容就是所绑定的object的地址,而且上程序中用了间接的办法改了绑定关系,而且reference定义必须初始化看来也不是必须的?

哪位大神给讲讲是处于哪方面的考虑?
...全文
104 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
风划雪月 2014-11-25
  • 打赏
  • 举报
回复
C++ 创始人写的 the C++.Programming.Language.The.4th.Edition 中的7.7章节解释了所有的疑惑
风划雪月 2014-11-25
  • 打赏
  • 举报
回复
引用 1 楼 ri_aje 的回复:
先把基础打牢靠吧,主楼程序搞来搞去都是指针,和 reference 木啥必然联系。 至于 reference 为啥绑定后就不能改变绑定了,简而言之就是个语言的规定,从道理上讲,改变绑定的功能已经由指针提供了,语言要真是允许引用能够重新绑定,到时候你又要问为啥引用和指针功能重叠了。
这算是回答吗?我相信这样的规定是有背后的原因的,我要问的就是这个原因? 我只是用指针实间接实现了改变引用的办法,而你却纠结我用什么实现了改变引用。指针和引用的功能重叠吗?我觉得引用至少 “解引用的语法”
ri_aje 2014-11-25
  • 打赏
  • 举报
回复
先把基础打牢靠吧,主楼程序搞来搞去都是指针,和 reference 木啥必然联系。 至于 reference 为啥绑定后就不能改变绑定了,简而言之就是个语言的规定,从道理上讲,改变绑定的功能已经由指针提供了,语言要真是允许引用能够重新绑定,到时候你又要问为啥引用和指针功能重叠了。

64,651

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧