我正在尝试创建一个动态矩阵的模板类。以我目前对 C++ 的了解,我设法解决了一些问题,但我陷入了复制构造函数和重载 operator=; 的困境。换句话说,我无法创建我的对象的副本。在我看来,这应该可行,但我的朋友编译器告诉我,我有 1 个错误:错误:将 'const Matrix' 作为 'int Matrix::getElement(int, int) [with T = int 的 'this' 参数传递]' 在此行丢弃限定符 [-fpermissive]:
m[i][j] = original.getElement(i, j);
当我想创建一个对象时:
Matrix<int> m = Matrix<int>(3, 3);
我的模板类在这里:
template<class T>class Matrix
{
public:
Matrix<T>(int lines, int columns)
{
this->lines = lines;
this->columns = columns;
T* aux = new T[this->lines * this->columns];
m = new T*[lines];
for (int i = 0; i < this->lines; i++)
{
m[i] = aux + (i * this->columns);
}
for (int i = 0; i < this->lines; i++)
{
for (int j = 0; j < this->columns; j++)
{
m[i][j] = 0;
}
}
}
Matrix<T>(const Matrix<T>& original)
{
columns = original.getColumns();
lines = original.getLines();
T* aux = new T[this->lines * this->columns];
m = new T*[lines];
for (int i = 0; i < lines; i++)
{
m[i] = aux + (i * this->columns);
}
for (int i = 0; i < lines; i++)
{
for (int j = 0; j < columns; j++)
{
m[i][j] = original.getElement(i, j);
}
}
}
virtual ~Matrix<T>()
{
/*for (int i = lines - 1; i > 0; i--)
{
delete m[i];
}*/
delete [] m;
}
T** getPointer()
{
return m;
}
int getLines () const
{
return lines;
}
int getColumns () const
{
return columns;
}
int getElement(int line, int column)
{
return m[line][column];
}
int setElement(int line, int column, T value)
{
m[line][column] = value;
}
Matrix<T>* getTranspose()
{
Matrix<T>* aux = new Matrix<T>(lines, columns);
for (int i = 0; i < lines; i++)
{
for (int j = 0; j < columns; j++)
{
aux->setElement(i,j, m[j][i]);
}
}
return aux;
}
Matrix<T> operator=(const Matrix<T> original)
{
columns = original.getColumns();
lines = original.getLines();
T* aux = new T[this->lines * this->columns];
m = new T*[lines];
for (int i = 0; i < lines; i++)
{
m[i] = aux + (i * this->columns);
}
for (int i = 0; i < lines; i++)
{
for (int j = 0; j < columns; j++)
{
m[i][j] = original.getElement(i, j);
}
}
}
friend std::ostream& operator<<(std::ostream& out, Matrix<T>& matrix)
{
out<<"Matrix:"<<std::endl;
for (int i = 0; i < matrix.getLines(); i++)
{
for (int j = 0; j < matrix.getColumns(); j++)
{
out<<matrix.getElement(i, j)<<" ";
}
out<<std::endl;
}
return out;
}
friend std::istream& operator>>(std::istream& in, Matrix<T>& matrix)
{
std::cout << "Reading Matrix:\n";
for (int i = 0; i < matrix.getLines(); i++)
{
for (int j = 0; j < matrix.getColumns(); j++)
{
std::cout << "Matrix[" << i << "][" << j << "]:";
in >> matrix.m[i][j];
}
std::cout << std::endl;
}
return in;
}
private:
T** m;
int lines;
int columns;
};
正如我从该错误中可以看出的那样,我正在创建 2 个引用同一内存块的对象,但我想创建 2 个引用具有相同内容的 2 个不同内存块的对象。