C++ 操作员(&;)与参考操作员(&;)的地址
我对这个案子有点困惑: 声明一个指针:C++ 操作员(&;)与参考操作员(&;)的地址,c++,C++,我对这个案子有点困惑: 声明一个指针: int b =10; int*a=&b; 这里&取b的地址 考虑另一个例子: /* Reference to the calling object can be returned */ Test& Test::func () { // Some processing return *this; } 这应该是一个指针,*这是指向的对象。 但在这里,我们要求将*分配给&Test 我们应该如何修改代码以让函数返回地址。如果我们
int b =10;
int*a=&b;
这里&取b的地址
考虑另一个例子:
/* Reference to the calling object can be returned */
Test& Test::func ()
{
// Some processing
return *this;
}
这应该是一个指针,*这是指向的对象。
但在这里,我们要求将*分配给&Test
我们应该如何修改代码以让函数返回地址。如果我们仍然使用Test&?首先,
这是一个指针。*
取消对指针的引用,这意味着返回*this代码>返回对象,而不是指向该对象的指针
其次,Test&
返回对Test
实例的引用。在您的情况下,它是对对象的引用。要使其返回指针,它应该是Test*
如果从右向左读取指针声明,则更有意义
Test* func(); //When I call func, and dereference the returned value, it will be a Test
但这里我们要求将*此
分配给&测试
不。。。您要求使用值/表达式*this
返回测试&
,它是对测试
对象的引用。它的作用是返回对调用func()
的对象的引用
我们应该如何修改代码以让函数返回地址。我们是否仍应使用测试&
您应该使用Test*
来代替。。。指针是地址,并且已经改变了返回类型,可以返回代码< > <代码>(这是指针),但不是<代码> *这个< /C> >因为<代码> *这个< /C>不是指针。C++中的< P>有两个不同的语法单元:
&variable; // extracts address of variable
及
简单使用示例:
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
intv=5;
无法使其返回指针。请注意和的位置:在测试和中,它位于右侧,但在&b
中,它位于左侧。同样重要的是,Test
是一种类型,而b
是一个对象/变量。键盘上只有这么多键,字母和数字已经有了其他用途。另一方面,没有所谓的“引用操作符”操作符< /代码>有特定的含义,它适用于表达式而不是类型。@ Valand,虽然是一个好的观察,但这不是一个好的规则,因为这是完全随意的。我最喜欢的例子是f(int*&a)
或f(int*&a)`。这是什么?有人可能永远不会知道。@henrikgiesel这肯定是f(int*&a)
,即通过引用传递给函数f()
的指针。对于在正文中分配内存(或因任何其他原因更改地址)的函数,它是使用指针到指针(即f(int**a)
)的合理替代方法
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