c ++通过const引用 [英] c++ passing by const reference

查看:201
本文介绍了c ++通过const引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下程序中,指针的向量的主体cosists。 Points是x,y,z坐标和point_id的结构。我相信身体通过const引用,下面的步骤应该会产生一个错误。 BUt程序运行没有任何问题。你能请解释我为什么是这个。

In the following program body cosists of a vector of pointers. Points is a struct of x,y,z coordinates and a point_id. I believe as body is passed by const reference, the following step should produce an error. BUt the program is running without any problem. Can you please explain me why is this.

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

    ....

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


推荐答案

p>

Here's the issue:

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

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

Indirecting through a pointer removes any constness; rather, the constness of the result is dependent on the type of the pointer.

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引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆