无法将 valarray 初始化为类的私有成员

Can't initialize valarray as private member of class

本文关键字:成员 valarray 初始化      更新时间:2023-10-16

我试图实现一个类,其中包含一个valarray和2个int定义其大小。我的hpp文件看起来像这样:

class Matrix
{
public:
    // Constructors
    Matrix();
    Matrix(int width, int height);
    // Mutators
    void setWidth(int width);               // POST: width of the matrix is set
    void setHeight(int height);             // POST: height of the matrix is set
    //void initVA(double width);
    // Accessors
    int getWidth();                         // POST: Returns the number of columns in the matrix
    int getHeight();                        // POST: Returns the number of rows in the matrix
    // Other Methods
    //void printMatrix(const char* lbl, const std::valarray<double>& a);
private:
    int width_;
    int height_;
    std::valarray<double> storage_;
};

但是,当我尝试像这样在构造函数上初始化valarray时:

Matrix::Matrix(int width, int height)
{
    width_ = width;
    height_ = height;
    storage_(width*height);
}

我一直得到这个错误信息:

错误C2064: term不计算为带有1个参数的函数

文档说我可以用至少5种不同的方式声明一个valarray,但是只有默认的构造函数有效。我到处都找遍了,但没能找到任何有用的信息。

您实际上试图在这里调用std::valarray<double>::operator()(int),但不存在这样的操作符。大概,您打算使用初始化列表来代替:

Matrix::Matrix(int width, int height)
    : width_(width),
      height_(height),
      storage_(width*height)
{
}

或者,您可以分配一个新的对象实例,但这将比使用初始化列表性能更低,因为storage_将被默认构造,然后用新临时对象的副本替换,最后临时对象将被销毁。(一个体面的编译器可能能够消除这些步骤中的一些,但我不会依赖它。)

storage_ = std::valarray<double>(width*height);