【发布时间】:2012-07-14 06:26:20
【问题描述】:
可能重复:
C++ functions: ampersand vs asterisk
What are the distinctions between the various symbols (*,&, etc) combined with parameters?
我想知道 C++ 函数调用中地址运算符 & 和尊重运算符 * 之间的区别。比如下面的函数
void foo (std::string& param)
{
param = "Bar.";
std::cout << param.size();
}
让我们在 main() 函数中这样调用它......
int main()
{
std::string test;
foo(test); //Why not foo(&test)?
std::cout << test; //Prints out the value "Bar."
}
首先,为什么& 运算符允许我像指针一样分配一个值(当它不是指针时,分配一个在函数foo() 的RAII 和范围内幸存的值)因为它即使不是static,也可以在我的main() 函数中打印出来?我假设它不是指针,因为我可以通过使用. 运算符而不是用于指针的-> 来访问size() 方法。
其次,在函数参数中使用& 运算符与使用* 运算符有什么区别?它甚至与像std::string param 这样的普通变量不同吗?它似乎是这样称呼的(foo(test) 而不是foo(&test))。
【问题讨论】:
-
深入了解 C++ references。
-
不是算子,是参考。
标签: c++ function dereference address-operator