为了避免使用矩阵拷贝构造函数,可以采用以下解决方法:
class Matrix {
private:
int rows;
int cols;
int** data;
public:
Matrix(int r, int c) : rows(r), cols(c) {
data = new int*[rows];
for (int i = 0; i < rows; i++) {
data[i] = new int[cols];
}
}
// 使用引用传递
Matrix(const Matrix& other) {
rows = other.rows;
cols = other.cols;
data = new int*[rows];
for (int i = 0; i < rows; i++) {
data[i] = new int[cols];
for (int j = 0; j < cols; j++) {
data[i][j] = other.data[i][j];
}
}
}
~Matrix() {
for (int i = 0; i < rows; i++) {
delete[] data[i];
}
delete[] data;
}
// 其他成员函数和操作符重载...
};
class Matrix {
private:
int rows;
int cols;
int** data;
public:
Matrix(int r, int c) : rows(r), cols(c) {
data = new int*[rows];
for (int i = 0; i < rows; i++) {
data[i] = new int[cols];
}
}
// 移动构造函数
Matrix(Matrix&& other) noexcept {
rows = other.rows;
cols = other.cols;
data = other.data;
other.data = nullptr;
}
~Matrix() {
for (int i = 0; i < rows; i++) {
delete[] data[i];
}
delete[] data;
}
// 其他成员函数和操作符重载...
};
// 使用移动语义创建对象
Matrix createMatrix() {
Matrix temp(3, 3);
// 初始化矩阵...
return temp;
}
int main() {
Matrix m1 = createMatrix(); // 使用移动构造函数
return 0;
}
通过使用引用传递或移动语义,可以避免不必要的矩阵拷贝构造函数的调用,提高程序的性能和效率。
下一篇:避免使用kable重叠的列