【问题标题】:error: size in array new must have integral type [-fpermissive]错误:新数组中的大小必须具有整数类型 [-fpermissive]
【发布时间】:2016-08-28 07:33:39
【问题描述】:

我正在使用动态内存分配来创建新对象,当我尝试编译时,以下错误不断出现。我将维度_创建为无符号整数,所以我不确定为什么会出现此错误。

EuclideanVector.h:69:40: error: size in array new must have integral type [-fpermissive]
                         magnitude_  =  new double [dimensions_];

以下是错误指向的代码:

// target constructor for delegating constructor
template <typename NUM1, typename NUM2> // any numeric types of user input for dimensions and magnitude will be static_cast to unsigned int and double respectively
EuclideanVector(const NUM1 dimensions, const NUM2 magnitude){

            // static cast to unsigned int for temp and assign dimensions_ to that
            unsigned int temp = static_cast<unsigned int>(dimensions);
            dimensions_ = new unsigned int (temp);

            // assign pointer "magnitude_" to dynamically-allocated memory of new unnamed array<double> object of size "dimensions_"
            magnitude_  =  new double [dimensions_];

            // fill the array<double> object "magnitude_" a number of "dimensions_" times, with the <double> value of "magnitude_" for each dimension
            std::fill_n(magnitude_, dimensions_, static_cast<double>(magnitude));

            updateNormal();
      }

【问题讨论】:

  • 这个模板怎么称呼?
  • 我使用委托构造函数:template EuclideanVector(const NUM dimensions = 1): EuclideanVector(dimensions, 0.0) {};
  • 请在您的问题中提供minimal reproducible example,以重现问题。
  • dimensions_ = new unsigned int (temp); --- 为什么?为什么不直接使用std::vector&lt;double&gt; magnitude_ 而忘记整个new[] 的事情呢?
  • @iteong -- 这里没有任何理由使用newdimensions_ = new unsigned int (temp);。如果您动态分配一个 int 而不是仅仅声明一个 int,那么您已经完全过火了。

标签: c++ arrays dynamic-memory-allocation integral function-templates


【解决方案1】:

dimensions_ 是一个指针,而不是 unsigned int,从 new unsigned int (temp); 返回。
你需要类似magnitude_ = new double [*dimensions_];

【讨论】:

    【解决方案2】:

    您不能将指针用作数组大小。

    “在运行时计算大小的数组”的一般解决方案是使用std::vector

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 2021-09-11
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      相关资源
      最近更新 更多