gpt4 book ai didi

c++ 通过 const 引用传递

转载 作者:IT老高 更新时间:2023-10-28 21:48:49 27 4
gpt4 key购买 nike

在下面的程序体中包含一个指针 vector 。 Points 是 x,y,z 坐标和 point_id 的结构。我相信由于 body 是通过 const 引用传递的,因此以下步骤应该会产生错误。但是程序运行没有任何问题。你能解释一下为什么会这样吗?

void readOutFile(const Body& body, int n){

....

body.bp[0]->points.push_back(Point_id(p,i));
}

最佳答案

问题来了:

body.bp[0]->points.push_back(Point_id(p,i));
^^

通过指针间接删除任何常量;相反,结果的常量取决于指针的类型。

T *t;              // pointer to T: can modify t and (*t)
const T *t; // pointer to const-T: can modify t but not (*t)
T *const t; // const-pointer to T: can modify (*t) but not t
const T *const t; // const-pointer to const-T: can't modify either t or (*t)

关于c++ 通过 const 引用传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10976702/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com