我的问题涉及以下继承自ifstream的Bifstream成员函数。 读取需要一个字符指针。我给它 (char*)&target。 target 是一个引用,所以我给它的是对 int 引用的引用。为什么会这样?
bool cBifstream::ReadInt( int& target ){
if( !this->is_open() ){
return false;
}
this->read( (char*)&target, sizeof(int) );
}
这是我使用的其他工作代码的片段。
int size;
is.read((char*)&size, sizeof(int));
语法相同,但这次变量是一个 int 而不是对 int 的引用。
目标声明:
cBifstream a("test2");
int b;
a.ReadInt(b);
编辑: 感谢您的答复。 我仍然不明白一件事。
this->read( (char*)target, sizeof(int) ); (all i did here was remove the ampersand)
此更改导致我的程序崩溃。但是 target 是对 int 的引用,所以上面应该可以工作,因为
int size;
is.read((char*)&size, sizeof(int));
有效。
最佳答案
您正在获取引用的地址 - 这会生成 target
所引用的变量的地址。引用是它引用的变量的别名,任何地方都没有语法间接 - 因此对引用执行的任何操作都会影响引用的变量。
int x;
int & y=x;
使用上面的方法,你对 y
做的任何事情都将像你对 x
关于引用和按引用传递参数之间的 C++ 区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5896354/