将值传递给常量引用参数?
题
我在这里或通过谷歌找不到类似的问题,也许是因为我不知道我是否问了正确的问题,所以不确定标题是否正确。但我正在使用如下代码:
Foo * foo = new Foo();
add(*foo); //Couldnt find any similar questions on this syntax?
void add(const Foo & foo){
//What exactly is foo here? How can i manipulate its members, foo. or foo-> ?
}
解决方案
变量 foo
在 - 的里面 add
方法是一个恒定的参考。它的行为类似于指针,因为它不复制对象:你与它互动,就好像它是物体本身一样。与指针不同,引用不能 NULL
, ,并且不能重新分配。您可以使用点与其进行交互 .
运算符而不是 ->
操作员。
void add(const Foo & foo){
cout << foo.first_member << endl;
foo.const_member_function();
}
自从 foo
是一个常量参考,你可以阅读 foo
的成员,但您不能分配他们。此外,对成员函数的任何调用 foo
引用仅限于明确标记的函数 const
.
呼唤 add
带有取消引用的 foo
就可以了,只要 foo
不是 NULL
. 。通过取消引用来进行引用 NULL
指针是未定义的行为。
其他提示
'foo' is a constant reference. You can access its members via foo.fred, foo.method(), etc., but you can't change any data members or call any non-const methods.
不隶属于 StackOverflow