本文介绍了可变大小的对象可以不被初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样一类
类ACLASS
{
上市:
ACLASS():N(5){}
无效aMemberFunction()
{
INT NUMS [N] = {1,2,3,4,5};
}
私人的:
const int的N;
};
测试code是
INT的main()
{
ACLASS A;
A.aMemberFunction(); const int的N = 5;
INT整数[N] = {5,4,3,2,1};
返回0;
}
当我编译(G ++ 4.6.2 20111027),我得到的错误
problem.h:在成员函数'无效ACLASS :: aMemberFunction():
problem.h:7:31:错误:可变大小的对象NUMS可能无法初始化
如果我注释掉的行 INT NUMS [N]
我没有得到一个编译错误,所以类似code为整数
数组是罚款。是不是值 N
在编译的时候知道的?
这是怎么回事?为什么 NUMS
视为一个可变大小的数组?为什么阵列 NUMS
和整数
处理方式不同?
解决方案
No. At the time aMemberFunction
is compiled, the compiler does not now what N
is, since its value is determined at run-time. It is not smart enough to see that there is only one constructor, and assumes that the value of N
could be different than 5.
这篇关于可变大小的对象可以不被初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!