gpt4 book ai didi

模板类中的 C++ 赋值运算符实现

转载 作者:行者123 更新时间:2023-11-30 04:36:42 25 4
gpt4 key购买 nike

我正在构建自己的矩阵类以巩固我对 C++ 的理解。它是模板化的,所以我可以有一个 int 矩阵或一个 float 或 boolean 矩阵。我不打算实现复制构造函数或赋值运算符或析构函数,因为我不会有任何动态成员元素,但如果我有:

Matrix<float,3,4> mat1;
Matrix<int,45,45> mat2;
mat1 = mat2;

它返回以下错误:

/Users/Jake/Dropbox/C++/test.cpp: In function ‘bool test1()’:
/Users/Jake/Dropbox/C++/test.cpp:23: error: no match for ‘operator=’ in ‘m2 = m1’
/Users/Jake/Dropbox/C++/Matrix.h:22: note: candidates are: Matrix<float, 3u, 4u>& Matrix<float, 3u, 4u>::operator=(const Matrix<float, 3u, 4u>&)

其中,如果两个矩阵都是float或者都是int,就可以了。尺寸不必匹配。所以默认的赋值运算符工作得很好,除非它们是不同的类型。所以我实现了自己的赋值运算符:

template <class T, unsigned int rows, unsigned int cols>
template <class T2, unsigned int rows2, unsigned int cols2>
Matrix<T, rows2, cols2> & Matrix<T,rows,cols>::operator= (const Matrix<T2, rows2, cols2> & second_matrix){
unsigned int i,j;
for (i=0; i < rows2; i++){
for (j=0; j < cols2; j++){
data[i][j] = second_matrix(i,j);
}
}
this->_rows = rows2;
this->_cols = cols2;
return *this;
}

如果它们是不同类型但维度相同,则此方法有效 - 但第二个中的值从第二种类型转换为第一种。我的问题是,如何设置它以便它们可以是不同的类型和不同的维度,并将其设置为指向第二个或第二个的拷贝?

最佳答案

你遇到的问题是你有三种类型,但你只提到了两种。从根本上说,

Matrix<float,3,4> mat1;
Matrix<int,45,45> mat2;
mat1 = mat2;

不行,因为赋值的结果应该是Matrix<float, 45, 45> ,但是mat1类型为 Matrix<float, 3, 4> .这不可能改变。

矩阵的维度必须是类型的一部分是否有原因?看起来你真的想让这些东西动态地改变。只是做:'

template <class T>
class Matrix
{
unsigned int rows;
unsigned int cols;
public:
Matrix(numrows, numcols): rows(numrows), cols(numcols) {}
};

等等... 然后您可以让矩阵的维度在运行时发生变化。

关于模板类中的 C++ 赋值运算符实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4403923/

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