引用和引用传递参数之间的C++差异

Dan*_*iel 2 c++ arguments reference

我的问题涉及继承自ifstream的Bifstream的以下成员函数.Read需要一个char指针.我给它(char*)和目标.target是一个引用,所以我给它的是对int的引用的引用.为什么这样做?

bool cBifstream::ReadInt( int& target ){
    if( !this->is_open() ){
        return false;
    }
    this->read( (char*)&target, sizeof(int) );
}
Run Code Online (Sandbox Code Playgroud)

这是我使用的其他工作代码的片段.

int size;
is.read((char*)&size, sizeof(int));
Run Code Online (Sandbox Code Playgroud)

语法是相同的,但这次变量是一个int而不是对int的引用.

目标声明:

cBifstream a("test2");
int b;
a.ReadInt(b);
Run Code Online (Sandbox Code Playgroud)

编辑:谢谢你的回复.我还是不明白一件事.

this->read( (char*)target, sizeof(int) );  (all i did here was remove the ampersand)
Run Code Online (Sandbox Code Playgroud)

此更改导致我的程序崩溃.但是target是对int的引用,所以上面应该有效

int size;
is.read((char*)&size, sizeof(int));
Run Code Online (Sandbox Code Playgroud)

作品.

Eri*_*rik 6

您正在获取引用的地址 - 这将生成变量target引用的地址.引用是它引用的变量的别名,在任何地方都没有语法间接 - 因此对引用执行的任何操作都会影响引用的变量.

int x; 
int & y=x;
Run Code Online (Sandbox Code Playgroud)

使用上述内容,您所做的任何事情都y将完全像您所做的那样工作x