简体   繁体   English

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

[英]C++ How to pass a vector of pointers (double pointers) as a constant to a function

I have a class A in C++ with many attributes: 我在C ++中有一个具有许多属性的A类:

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

In a third class C , there is a function that uses the tab variable as input, reads each element and does some calculations to write results on another attribute of the class C : 在第三类C ,有一个函数使用tab变量作为输入,读取每个元素,并进行一些计算以将结果写入类C另一个属性:

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

How can I make tab : the vector of pointers protected (or constant) ? 我怎样才能tab :指针的向量受保护(或常量)?

One possible way is something like this: 一种可能的方式是这样的:

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

Or you can ban changing even pointer to pointers like this: 或者,您可以禁止更改甚至如下所示的指针:

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

If you need to protect only pointers in array the first example is your choice 如果只需要保护数组中的指针,则选择第一个示例

How about using vector : 如何使用vector

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM