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定义必须初始化看来也不是必须的?
哪位大神给讲讲是处于哪方面的考虑?