"&"符号在函数的返回类型中是什么意思?
What does the "&" symbol mean in the return type of a function?
我正在读一本C++书,它解释了以下函数:
istream& read_hw(istream& in, vector<double>& hw) {
if (in) {
hw.clear() ;
double x;
while (in >> x)
hw.push_back(x);
in.clear();
}
return in;
}
这本书解释说,参数列表中的"&"意味着它们是通过引用传递的,但在函数的返回类型中,istream&
中没有关于该符号的解释
删除它会导致许多编译错误。有人能澄清吗?
函数也通过引用返回。在这种情况下,您传入的对象是从函数返回的,因此您可以"连锁"调用此函数:
in.read_hw(hw1).read_hw(hw2);
这是C++中常见的模式,尤其是在使用IOstreams库时。
这将返回对istream的引用。注意,这可能与istream&作为参数传递的引用。
来自learncpp.com:
通过引用返回通常用于将通过引用传递给函数的参数返回给调用方。在下面的例子中,我们(通过引用)返回一个数组的元素,该元素通过引用传递给我们的函数:
// This struct holds an array of 25 integers
struct FixedArray25
{
int anValue[25];
};
// Returns a reference to the nIndex element of rArray
int& Value(FixedArray25 &rArray, int nIndex)
{
return rArray.anValue[nIndex];
}
int main()
{
FixedArray25 sMyArray;
// Set the 10th element of sMyArray to the value 5
Value(sMyArray, 10) = 5;
cout << sMyArray.anValue[10] << endl;
return 0;
}
在"istream&in"中;操作员的意思是"的参考"
只要知道,无论你在这里传递什么变量,原始值都会被修改
它是一个引用。它就像一个指针,但不能为NULL。
因此,您的函数返回对istream
对象的引用。请注意,您还向函数传递了与第一个参数相同的数据类型。
对流执行此操作非常常见,因此您可以使用流测试运算符来检查错误条件:
if( !read_hw(in, hw) ) cerr << "Read failedn";
相关文章:
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- 标准 N3337 5.2.10 第 7 条中的C++"类型"是什么意思?
- "类模板示例<int>;"语句对 C++11 是什么意思?
- 线应该是什么意思
- "CID"在AT+HTTPPARA= "CID" ,1中是什么意思
- 表达式"b=(b-x)&x"是什么意思?
- 这个表达是什么意思?
- 此代码验证公式是什么意思?
- 跟踪日志中的T.11803()是什么意思?
- 这个额外的关键字在这个 c++ 类声明中是什么意思?
- * 和 ** 在 C++ 函数声明中是什么意思?
- _T("xyz")是什么意思?
- #define Dbg(fmt,..) (0) 是什么意思? 警告:表达式无效
- 这行代码到底是什么意思?
- 在命名空间名称之前加上 :: 是什么意思?
- 从字符数组的元素中减去'a'是什么意思
- "friend"关键字在C++中是什么意思?
- 减法中的"0"是什么意思?
- 字符数组前面的加号是什么意思?
- 这里的字符串函数是什么意思