c++ - 这个例子在 Bjarne Stroustrup 的 C++ 编程语言中是如何工作的?

标签 c++ reference constants pass-by-reference

我正在阅读 The C++ Programming Language, 4th Edition (通过 Bjarne Stroustrup )关于 .

他有以下代码示例:

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/

相关文章:

c++ - 如何创建类对象的 vector vector

javascript - 就声明而言,Javascript 中 for of 循环中的 let 和 const 之间没有区别吗?

c++ - 如何初始化一个长度等于 const int 方法返回值的数组?

java - 为什么引用数据类型是指向的?

php - Laravel -- 为什么 `::class` 常量

c++ - std::ctype 是否总是按 "C"语言环境对字符进行分类?

c++ - 如何在MFC编程中使用GetDHtmlDocument()?

c++ - 空函数宏

c++ - 如何取消引用在 C++ 中通过引用传递的指针?

c# - 为什么字符串不比较引用?