C ++如何将指针(双指针)的向量作为常量传递给函数

时间:2017-02-02 21:50:07

标签: c++ pointers vector

我在C ++中有一个具有许多属性的类A

 class A{
   public:
      B** tab;// B is another class or structure
      ....
      void compute();//this function does calculations on elements inside tab
   };

在第三个类C中,有一个函数使用tab变量作为输入,读取每个元素并进行一些计算以将结果写入类C的另一个属性:

C::compute(B** tab){
     ....// I need that **tab be protected inside this function and its elements does not change
 }

如何制作tab:指针的矢量受保护(或常量)?

2 个答案:

答案 0 :(得分:1)

一种可能的方式是这样的:

C::compute(B * const * tab){
   // nothing in this array of pointers will be changed
   tab[0] = (B *) 0x3254; // compile error as desired
}

或者您可以禁止更改指针指向这样的指针:

C::compute(B * const * const tab){
   // nothing in this array of pointers will be changed
   tab = (B * const *) 0x3254; // compile error
}

如果你只需要保护数组中的指针,那么第一个例子就是你的选择

答案 1 :(得分:0)

如何使用vector

class A {
    vector<vector<B> > tab;
    //...
}

C::compute(const vector<vector<B> >& tab) {
    // tab, tab[0] and tab[0][0] are all const
}
相关问题