代码片段:
class Block
{
  Block(int width)
  {
    int number_list[width][width]={{0,},};
  }
  void text_print()
  {
    for(auto i:number_list)
      {
        std::cout << i << ' ';
      }
  }
}
我在创建 class 以后,直接使用构造函数创建了一个数组 number_list ,这个数组是要在整个 class 里面到处都用的,但是构造函数本身不能用 return ,不知道如何把 number_list 变成全局变量,方便其他函数使用?
我尝试过 static ,但是编译器报错,因为我这个数组的长度本身是运行时才确定的。
错误:‘ number_list ’的存储大小不是常量
     static int number_list[width][width]={{0,},};
|  |      1hyq      2015-11-26 16:21:42 +08:00 template<int Width> class Block { int number_list[Width][Width]; } 这个得在编译期确定大小。 | 
|  |      2hxsf      2015-11-26 16:22:24 +08:00 静态的数组变量 number_list 创建的时候根本不知道 width 是多少,所以报错。 正常做法不是应该定义一个类元素(或者叫类属性) 然后构造函数里面把外部传进来的数组赋值给自己内部的数组么 | 
|  |      3xujif      2015-11-26 16:22:37 +08:00 class Block { protected: int **number_list; Block(int width) { this->number_list = new [width][width]; } ~Block() { delete[] this->number_list } } | 
|      4cfans1993      2015-11-26 16:26:00 +08:00 如果没理解错的话,你是想把 number_list 作为成员变量使用,那就声明在类里就好了 class Block{ ... private int **number_list; //int number_list[10][10] } 然后在构造函数 Block(int width)中初始化 另外数组好像要在定义时指定长度,如果需要动态指定长度的话要用指针,然后在构造函数中 new 一下 | 
|  |      5linux40      2015-11-26 16:27:53 +08:00 为什么不使用标准库里面的 std::array(编译时确定大小)或 std::vector 或 std::unique_ptr , c++不同于 c ,不能在运行时确定数组大小。 | 
|  |      6fyyz OP @cfans1993 数组是可以在运行时指定长度的,不然 main(int argc,char *argv[]) 是怎么起作用的? | 
|  |      7liberize      2015-11-26 16:45:57 +08:00 via iPhone 如果用类模板需要 width 是常量,如果用二级指针需要把 width 用成员变量保存下来,后面遍历的时候使用 | 
|  |      8fyyz OP | 
|  |      9liberize      2015-11-26 16:51:01 +08:00 via iPhone @fyyz 不要在栈上创建变长数组,另外 char *argv[] 等价于 char **argv ,跟这个没有关系 | 
|  |      11fyyz OP @liberize 加了 int 也不行,报错说 array size in new-expression must be constant 。看来数组长度必须被确定。 | 
|  |      13liberize      2015-11-26 16:57:37 +08:00 | 
|  |      14GentleSadness      2015-11-26 17:16:12 +08:00 via Android 为何不直接在外面搞个数组呢,智能指针不怕 delete |