gpt4 book ai didi

c++ - 无法将 valarray 初始化为类的私有(private)成员

转载 作者:行者123 更新时间:2023-11-28 00:45:24 25 4
gpt4 key购买 nike

我正在尝试实现一个包含 valarray 和 2 个定义其大小的整数的类。我的 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);
}

我不断收到此错误消息:

error C2064: term does not evaluate to a function taking 1 arguments

The documentation说我可以用至少 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);

关于c++ - 无法将 valarray 初始化为类的私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16445498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com