代码片段:
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,},};
1
hyq 2015 年 11 月 26 日
template<int Width>
class Block { int number_list[Width][Width]; } 这个得在编译期确定大小。 |
2
hxsf 2015 年 11 月 26 日
静态的数组变量 number_list 创建的时候根本不知道 width 是多少,所以报错。
正常做法不是应该定义一个类元素(或者叫类属性) 然后构造函数里面把外部传进来的数组赋值给自己内部的数组么 |
3
xujif 2015 年 11 月 26 日
class Block
{ protected: int **number_list; Block(int width) { this->number_list = new [width][width]; } ~Block() { delete[] this->number_list } } |
4
cfans1993 2015 年 11 月 26 日
如果没理解错的话,你是想把 number_list 作为成员变量使用,那就声明在类里就好了
class Block{ ... private int **number_list; //int number_list[10][10] } 然后在构造函数 Block(int width)中初始化 另外数组好像要在定义时指定长度,如果需要动态指定长度的话要用指针,然后在构造函数中 new 一下 |
5
linux40 2015 年 11 月 26 日
为什么不使用标准库里面的 std::array(编译时确定大小)或 std::vector 或 std::unique_ptr , c++不同于 c ,不能在运行时确定数组大小。
|
7
liberize 2015 年 11 月 26 日 via iPhone
如果用类模板需要 width 是常量,如果用二级指针需要把 width 用成员变量保存下来,后面遍历的时候使用
|
8
fyyz OP |
11
fyyz OP @liberize 加了 int 也不行,报错说 array size in new-expression must be constant 。看来数组长度必须被确定。
|
13
liberize 2015 年 11 月 26 日
|
14
GentleSadness 2015 年 11 月 26 日 via Android
为何不直接在外面搞个数组呢,智能指针不怕 delete
|