【发布时间】: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<double> magnitude_而忘记整个new[]的事情呢? -
@iteong -- 这里没有任何理由使用
new:dimensions_ = new unsigned int (temp);。如果您动态分配一个int而不是仅仅声明一个int,那么您已经完全过火了。
标签: c++ arrays dynamic-memory-allocation integral function-templates