【发布时间】:2018-02-11 05:14:17
【问题描述】:
规范说函数必须返回由[]中的“行号”指定的矩阵的行
类定义:
class Matrix
{
public:
//functions taken out
private:
double ** matrix; // the matrix array
unsigned rows; // # rows
unsigned cols; // # columns
};
简短的主要内容:
cout << "Test []: " << endl;
try {
Matrix row = m0[0]; //**m0 is Matrix m0(1,1); where the constructor creates the appropriate array**
cout << row << endl;
row = m0[1];
cout << row << endl;
row = m0[100]; // should throw an exception
} catch (const char * err) {
cout << err << endl;
}
函数实现:
double& Matrix::operator [](const unsigned int &sub)
{
if( sub >= rows)
{
const char * error = "Error: invalid row index";
throw error;
} else
{
return *matrix[sub];
}
}
重载
//This is working for my other displays so this shouldn't be the problem
ostream &operator << (ostream &ostrm, const Matrix &obj)
{
//Loop through to display
for(unsigned int i = 0; i < obj.rows; i++)
{
for(unsigned int j = 0; j< obj.cols; j++)
{
ostrm << setw(10) << setprecision(3) << obj.matrix[i][j];
}
ostrm << endl;
}
return ostrm;
}
重载 = 运算符:
//Again this works for everything else
Matrix& Matrix::operator=(const Matrix &rhs)
{
//Copy Rows and Cols
rows = rhs.rows;
cols = rhs.cols;
//If statement to check for self assignment
if(&rhs == this)
{
return *this;
}
else
{
delete [] matrix;
matrix = new double*[rows]; //Allocate Dynamic Array
//Deep copy elements by looping and copying each element
for(unsigned int i = 0; i < rows; i++)
{
matrix[i] = new double[cols];
for(unsigned int j = 0; j < cols; j++)
{
matrix[i][j] = rhs.matrix[i][j];
}
}
return *this;
}
}
我的输出:
Test []:
Error: invalid row index
预期输出:
Test []:
17.2 -3 -0.5 6
8.2 4 3 1
Error: invalid row index
我不确定为什么这些行没有显示或者甚至没有被存储。
提前致谢
【问题讨论】:
-
请显示
Matrix类定义。例如,matrix是什么?它是如何声明的?它是如何初始化的?最好尝试创建一个Minimal, Complete, and Verifiable Example。 -
它仍然不是Minimal, Complete, and Verifiable Example。
m0是什么?它是Matrix对象吗?当operator[]函数返回对单个double值 的引用时,你怎么能做到Matrix row = m0[0]?Matrix有哪些构造函数?您的移动或复制构造函数是否按应有的方式工作? -
另外,你关注the rules of three or five吗?或许你应该停止使用指针,改用
std::vector,然后改用the rule of zero? -
矩阵类需要大量时间来构建。你的到处都是错误和设计缺陷。为什么不使用 BLAS,可从 boost 发行版中获得?
-
错误?设计缺陷?如果我不知道它是错的,我就无法修复它?这是一个校队的任务,它必须实现这个..
标签: c++ overloading operator-keyword subscript