可变大小的对象可以不被初始化 [英] variable-sized object may not be initialized

查看:224
本文介绍了可变大小的对象可以不被初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一类

 类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 整数处理方式不同?


解决方案

  

是不是在编译时已知的 N 价值?


没有。当时 aMemberFunction 编译,编译器不现在是什么 N 是的,因为它的值在运行确定时间。这是不够聪明,看到只有一个构造函数,并假定的 N 的价值可能比5个不同的。

I have a class like this

class aClass
{
  public:
    aClass() : N(5) {}
    void aMemberFunction()
    {
      int nums[N] = {1,2,3,4,5};
    }
  private:
    const int N;
};

The testing code is

int main()
{
  aClass A;
  A.aMemberFunction();

  const int N = 5;
  int ints[N] = {5,4,3,2,1};
  return 0;
}

When I compile (g++ 4.6.2 20111027), I get the error

problem.h: In member function ‘void aClass::aMemberFunction()’:
problem.h:7:31: error: variable-sized object ‘nums’ may not be initialized

If I comment out the line with int nums[N] I don't get a compilation error, so the similar code for the ints array is fine. Isn't the value of N known at compile time?

What's going on? Why is nums considered a variable-sized array? Why are the arrays nums and ints handled differently?

解决方案

Isn't the value of N known at compile time?

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.

这篇关于可变大小的对象可以不被初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆