gpt4 book ai didi

c++ - 如何正确指定拷贝构造函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:04:00 34 4
gpt4 key购买 nike

假设我有一个矩阵类,其构造函数如下:

Matrix::Matrix(int rows, int cols)
{
nrows = a; //here nrows is the number of rows for each matrix
ncols = b; //here ncols is the number of cols for each matrix
p = new double [rows*cols];
for(int i=0;i<rows*cols;i++)
{
*p++ = 0.0;
}
}

假设我还有一个“复制”构造函数,如下所示:

Matrix::Matrix(const Matrix& mat)
{ p = new double[mat.nrows*mat.ncols];
for(int i=0;i<mat.nrows*mat.ncols;i++)
{
p[i] = mat.p[i];

}
}

现在假设我的 main 函数中有以下几行:

int main()
{
Matrix A(2,2);
Matrix B(2,2);
A = Matrix(B); //call overloaded assignment operator, and copy ctor/
}

此处“=”运算符被重载以将 B 中的所有元素分配给 A。我的问题是,一旦调用复制构造函数,Matrix A 对象就是一个全新的对象。

是否有更好的方法来编写复制构造函数,以便如果矩阵 A 已经存在,则调用 A = Matrix(B) 会导致错误?

最佳答案

我建议使用 std::vector

而不是使用动态分配的数组
class Matrix
{
public:
Matrix(long rows, long cols);
private:
long nrows;
long ncols;
std::vector<double> p;
}

那么你的构造函数可以是

Matrix::Matrix(long rows, long cols)
: nrows(rows),
ncols(cols),
p(rows * cols)
{ }

连同 all of the other benefits通过在动态分配的数组上使用 std::vector,您现在可以获得编译器生成的复制构造函数,因此您无需编写一个。

如果您不希望您的类可复制,请删除复制构造函数和复制赋值运算符。

class Matrix
{
public:
Matrix(long rows, long cols);
Matrix(const Matrix& mat) = delete;
Matrix& operator=(const Matrix& mat) = delete;
private:
long nrows;
long ncols;
std::vector<double> p;
}

关于c++ - 如何正确指定拷贝构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32099569/

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