我正在尝试为项目编写Matrix类。我将方阵分离为派生类。但是当我尝试对行列式执行次要操作时,我无法将矩阵成员分配给我的派生类对象。我该如何进行这些操作?实际上,我尝试了很多,但我无法取得成功。这是代码;
using namespace std;
class Matrix
{
friend ostream &operator<<(ostream &, const Matrix &);
friend istream &operator>>(istream &, const Matrix &);
private:
int num_col;
int num_row;
int **mits;
public:
Matrix(const int=0 ,const int=0);
Matrix (const Matrix &right);
~Matrix();
int DisplayMenu();
void gotoxy(int x, int y);
int getRow();
int getCol();
int** getMatrix();
virtual void print();
Matrix operator+(const Matrix&);
Matrix operator-(const Matrix&);
Matrix operator*(const Matrix&);
Matrix transMatrix(const Matrix&);
Matrix &operator=(const Matrix&);
};
#endif
# include <iostream>
# include "Matrix.h"
#include <windows.h>
# include <string>
using namespace std;
class SquareMatrix :public Matrix
{
int **sMits;
public:
SquareMatrix(const int=0 ,const int=0);
~SquareMatrix();
virtual void print();
SquareMatrix minor( const int,const int,const int);
int deter( SquareMatrix &mat);
/*SquareMatrix operator*(const SquareMatrix &);
virtual void print(const Matrix &);*/
};
SquareMatrix::SquareMatrix(const int row ,const int col)
:Matrix(row,col)
{
}
SquareMatrix::~SquareMatrix()
{
}
int SquareMatrix::deter(SquareMatrix &a)
{
SquareMatrix M;
int d = 0; // value of the determinant
int rows =a.getRow();
int cols =a.getCol();
sMits=a.getMatrix();
// this is a square matrix
if (rows == 1)
{
// this is a 1 x 1 matrix
d = sMits[0][0];
}
else if (rows == 2)
{
// this is a 2 x 2 matrix
// the determinant of [a11,a12;a21,a22] is det = a11*a22-a21*a12
d = sMits[0][0]* sMits[1][1] - sMits[1][0]* sMits[0][1];
}
else
{
rows--;
cols--;
for (int c = 0; c <= cols; c++)
{
M= minor(c,rows,cols);
d += (c%2 + c%2 - 1) * sMits[0][c] * deter(M);
}
}
return d;
}
SquareMatrix SquareMatrix::minor(const int col,const int rows,const int cols)
{
//int rows =Matrix::getRow();
//int cols =Matrix::getCol();
int **Mits=Matrix::getMatrix();
SquareMatrix min(rows , cols);
cout<<min<<endl;
for (int r = 1; r <= rows ; r++)
{
for (int c = 0; c <= cols ; c++)
{
if (c!=(col))
{
if (c<col)
{
min.sMits[r-1][c] = Mits[r][c];
}
else if (c>col)
{
min.sMits[r-1][c-1] = Mits[r][c];
}
}
}
}
return min;
}
void SquareMatrix::print()
{
Matrix::print();
}
答案 0 :(得分:1)
此代码存在很多问题,但我认为特别的问题是 min 是 SquareMatrix , SquareMatrix 构造函数调用 Matrix 构造函数,可能会初始化 Matrix :: mits ,但我没有看到 SquareMatrix :: sMits 被任何内容初始化。
无论如何,这一行
min.sMits[r-1][c] = Mits[r][c];
在 min 中访问 SquareMatrix :: sMits ,但 SquareMatrix :: sMits 未初始化,这会导致段错误/错误访问异常。您可能打算访问 Matrix :: mits ,但无法访问 Matrix :: mits 私有和 SquareMatrix 仅继承公开 矩阵。
如果您想在 min 中访问 SquareMatrix :: sMits ,则需要以某种方式填充 sMits ,或者提供对mits的受保护访问权限,并使用它。即。
class Matrix
{
protected:
int** mits;
然后
min.mits[r-1][c] = Mits[r][c];