C++ 的 class 里创建的构造函数怎么把局部的二维数组升级到 class 内部的全局二维数组?

2015-11-26 16:13:20 +08:00
 fyyz

代码片段:

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,},};
895 次点击
所在节点    C
14 条回复
hyq
2015-11-26 16:21:42 +08:00
template<int Width>
class Block
{
int number_list[Width][Width];
}

这个得在编译期确定大小。
hxsf
2015-11-26 16:22:24 +08:00
静态的数组变量 number_list 创建的时候根本不知道 width 是多少,所以报错。

正常做法不是应该定义一个类元素(或者叫类属性)
然后构造函数里面把外部传进来的数组赋值给自己内部的数组么
xujif
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
}


}
cfans1993
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 一下
linux40
2015-11-26 16:27:53 +08:00
为什么不使用标准库里面的 std::array(编译时确定大小)或 std::vector 或 std::unique_ptr , c++不同于 c ,不能在运行时确定数组大小。
fyyz
2015-11-26 16:45:29 +08:00
@cfans1993 数组是可以在运行时指定长度的,不然 main(int argc,char *argv[]) 是怎么起作用的?
liberize
2015-11-26 16:45:57 +08:00
如果用类模板需要 width 是常量,如果用二级指针需要把 width 用成员变量保存下来,后面遍历的时候使用
fyyz
2015-11-26 16:49:07 +08:00
@xujif 编译不过去
错误: expected type-specifier before ‘[’ token
this -> number_list = new [width][width];
liberize
2015-11-26 16:51:01 +08:00
@fyyz 不要在栈上创建变长数组,另外 char *argv[] 等价于 char **argv ,跟这个没有关系
liberize
2015-11-26 16:52:05 +08:00
@fyyz 明显少了 int 啊,建议楼主回去看看书
fyyz
2015-11-26 16:55:06 +08:00
@liberize 加了 int 也不行,报错说 array size in new-expression must be constant 。看来数组长度必须被确定。
liberize
2015-11-26 16:56:05 +08:00
@fyyz 。。。
liberize
2015-11-26 16:57:37 +08:00
GentleSadness
2015-11-26 17:16:12 +08:00
为何不直接在外面搞个数组呢,智能指针不怕 delete

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/239138

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX