我需要一些帮助来为我的类中的动态数组实现复制构造函数和 operator=。我此时不允许使用向量
这是我的代码: 类:
class Matrix{
private:
int rows;
int columns;
double* matrix;
public:
Matrix();
explicit Matrix(int N);
Matrix(int M, int N);
void setValue(int M, int N, double value);
double getValue(int M, int N);
bool isValid() const;
int getRows();
int getColumns();
~Matrix();
friend ostream& operator<<(ostream &out, Matrix&matrix1);
};
我的代码:
Matrix::Matrix(){
matrix = NULL;
}
Matrix::Matrix(int N){
matrix = new double[N * N];
rows = N;
columns = N;
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
if(i==j)
matrix[i * N + j] = 1;
else
matrix[i * N + j] = 0;
}
}
}
Matrix::Matrix(int M, int N){
matrix = new double[M * N];
rows = M;
columns = N;
for(int i = 0; i < M; i++){
for(int j = 0; j < N; j++)
matrix[i * N + j] = 0;
}
}
Matrix::~Matrix(){
delete [] matrix;
}
void Matrix::setValue(int M, int N, double value){
matrix[M * columns + N] = value;
}
double Matrix::getValue(int M, int N){
return matrix[M * columns + N];
}
bool Matrix::isValid() const{
if(matrix==NULL)
return false;
else
return true;
}
int Matrix::getRows(){
return rows;
}
int Matrix::getColumns(){
return columns;
}
ostream& operator<<(ostream &out, Matrix&matrix1){
if(matrix1.isValid())
for(int i = 0; i < matrix1.getRows(); i++){
for(int j = 0; j < matrix1.getColumns(); j++)
out << matrix1.getValue(i,j) << "\t";
out << endl;
}
else
out << "Matrisen er ikke gyldig."; //the matrix is not valid
return out;
}
像这样的东西会起作用吗?
Matrix &operator=(const Matrix &m) {*(this->matrix) = *(m.matrix);}
Matrix(const Matrix &rhs) : matrix(0) {
this->matrix = new double();
*(this->matrix) = *(rhs.matrix);
}
我还要重载运算符 += 和 +。我试图将其实现为:
const Matrix operator+=(Matrix matrix1, Matrix matrix2){
if(!matrix1.isValid() || !matrix2.isValid()){
cout << "En av matrisene er ugyldig"; //one of the matrices are invalid
return Matrix::Matrix(); //returning a NULL matrix
}
else{
if(matrix1.getColumns()==matrix2.getColumns() && matrix1.getRows()==matrix2.getRows()){
Matrix temp(matrix1.getRows(), matrix1.getColumns());
for(int i = 0; i < matrix1.getRows(); i++){
for(int j = 0; j < matrix1.getColumns(); j++)
temp.setValue(i,j,(matrix1.getValue(i,j) + matrix2.getValue(i,j)));
}
return temp;
}
else{
cout << "Matrisene har ikke samme dimensjon"; //the matrices does not have the same dimensions
return Matrix::Matrix();
}
}
}
const Matrix operator+(Matrix matrix1, Matrix matrix2){
return matrix1 += matrix2;
}
像这样的东西会起作用吗?将运算符重载为类的一部分、类的朋友还是类之外更好?
任何帮助都会得到帮助。