const正确性与指针结构 [英] const correctness for structs with pointers

查看:176
本文介绍了const正确性与指针结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些指点一个结构。我想,这些价值是不可修改的。但是,简单地写常量盈不作结构成员unmutable

I have a struct which contains some pointers. I want the value of these to be unmodifiable. But simply writing const infront doesn't make the structs members unmutable

typedef struct{
  int *x;
  int *y;
}point;

void get(const  point *p,int x, int y){
  p->x[0]=x;//<- this should not be allowed
  p->y[0]=y;//<- this should not be allowed
}

有人能指出我在正确的方向。

Can someone point me in the right direction.

编辑:

所以它似乎是有使用的函数原型告诉,一切都属于结构应该是不可修改的没有简单的方法

So it would seem that there is no simple way of using the function prototype to tell that everything belonging to the struct should be unmodifiable

推荐答案

要解释你需要建立的东西,当你写

To explain what you need to establish, when you write

point str;

point *p=&str;

下面的 p是一个指针STR 这类型的

在声明它为const,这意味着p是一个常量指针。这并不限制指针,该结构可以包含

When you declare it as const, it means that p is a constant pointer. This does not restrict the pointers that the structure may contain.

如果你想在常量内斯到结构内部应用,你必须定义结构也在里面指针为const

If you want the const ness to apply inside the structure, you have to define the pointers inside the structure also as const

typedef struct{
   const int *  x;
   const int *  y;
}point;

同样推回家时,我点声明参数为

Again to push home my point declare the parameter as

    void get(point * const  p,int x, int y) 
   //Constant Pointer ( *to prevent p from pointing to anything else*)

    //    AND

   //Make the pointers inside point structure constant
   //( *to prevent the int pointers x & y from pointing to anything else*)

如果它指向的结构也是const的使用

If the structure it is pointing to is also const use

      void get(const point * const p, int x, int y)
     //Constant Pointer to constant structure 

这篇关于const正确性与指针结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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