我对此案感到困惑:
声明一个指针:
int b =10;
int*a=&b;
Run Code Online (Sandbox Code Playgroud)
这里&取b的地址.
考虑另一个例子:
/* Reference to the calling object can be returned */
Test& Test::func ()
{
// Some processing
return *this;
}
Run Code Online (Sandbox Code Playgroud)
这应该是一个指针,*这是一个指向的对象.但在这里我们要求将*this分配给&Test.
我们应该修改代码以使函数返回地址.我们还应该使用Test&?
在C++中有两种不同的语法单元:
&variable; // extracts address of variable
Run Code Online (Sandbox Code Playgroud)
和
Type& ref = variable; // creates reference called ref to variable
Run Code Online (Sandbox Code Playgroud)
简单易用的例子:
int v = 5;
cout << v << endl; // prints 5
cout << &v << endl; // prints address of v
int* p;
p = &v; // stores address of v into p (p is a pointer to int)
int& r = v;
cout << r << endl; // prints 5
r = 6;
cout << r << endl; // prints 6
cout << v << endl; // prints 6 too because r is a reference to v
Run Code Online (Sandbox Code Playgroud)
至于在函数中使用引用,你应该google"在C++中通过引用传递",有很多关于它的教程.
首先,this是一个指针。取消*引用指针,意味着return *this;返回对象,而不是指向它的指针。
其次,Test&返回对实例的引用Test。就您而言,它是对该对象的引用。要使其返回一个指针,它应该是Test*.
如果从右向左阅读指针声明,则更有意义。
Test* func(); //When I call func, and dereference the returned value, it will be a Test
Run Code Online (Sandbox Code Playgroud)