我正在阅读 The C++ Programming Language, 4th Edition (通过 Bjarne Stroustrup )关于 references .
他有以下代码示例:
void f (const vector<double>& v){
double d1 = v[1];
v[2] = 7;
v.push_back(d1);
}
我的问题是:由于 v
是作为 const 传递的,我们如何才能在函数的第二个和第三个语句中更改 v
?
我尝试编译代码但它不起作用:
error: assignment of read-only location
那么我在这里缺少什么?我怀疑是 Bjarne 弄错了 :D
谢谢
最佳答案
更新后的版本有以下内容:
void f(vector<double>& v)
{
double d1 = v[1]; // copy the value of the double referred to by v.operator[](1) into d1
v[2] = 7; // place 7 in the double referred to by the result of v.operator[](2)
v.push_back(d1); // give push_back() a reference to d1 to wor k with
}
所以它可能已为下一次打印修复。
关于c++ - 这个例子在 Bjarne Stroustrup 的 C++ 编程语言中是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36678306/