【发布时间】:2020-03-29 02:01:55
【问题描述】:
我正在尝试使用重载运算符“+”和“=”来制作矩阵结构。
矩阵结构:
struct Matrix{
int rows;
int cols;
std::vector<int> data;
Matrix(int rows, int cols, int val); //creates matrix row*col and fills every position with val
Matrix(const Matrix &m); //copy constructor
Matrix(int rowcol = 0); //creates matrix rowcol*rowcol filled with zeros
Matrix & operator=(const Matrix &m);
void printMatrix(); //prints the matrix
...
};
运营商:
Matrix & Matrix::operator=(const Matrix &m) //assings matrix m to the new matrix
{
}
Matrix operator+(const Matrix &a, const Matrix &b) //sums two matrices
{
//I know how to make the algorithm for summing two matrices, however i don´t know how
//to return the result into existing matrix
}
主要功能:
int main(){
Matrix A(3,3,1);
Matrix B(3,3,2);
Matrix C(3,3,0);
C = A + B;
C.printMatrix();
...
return 0;
}
我不知道如何让它工作。我为“=”运算符尝试了类似的方法:
Matrix & Matrix::operator=(const Matrix &m)
{
static matrix d(m); //using copy constructor
return d;
}
但它不起作用。它创建了尺寸为 0x0 的新矩阵。关于如何实现它的任何建议?
【问题讨论】:
-
我在显示的矩阵类中看不到任何需要重载复制构造函数和赋值运算符的内容。您会发现,如图所示,复制该类的一个实例会起作用,就像变魔术一样。欢迎使用 C++!
-
Some reading on Sam's point。如果零规则特别有趣,但最好了解如何以及何时应用其他两个规则,因此您应该阅读整个内容。
-
关于尝试赋值运算符的注释。你几乎发现了Copy and Swap idiom。你出错的地方是赋值运算符应该赋值并返回
this,而不是本地对象,static或其他。
标签: c++ exception struct operator-overloading