c++ - 了解编写重载函数的代码(矩阵运算中的新 int[])
问题描述
昨天我们的讲师在没有任何有意义的解释的情况下给了我们下面的代码。我们正在努力理解它是如何工作的。
class Matrix {
static int mem;
int rows, cols;
int* ptr;
public:
Matrix(int l = 10, int k = 10) :rows(l), cols(k) {
ptr = new int[rows * cols];
mem += (rows * cols) * sizeof(int);
}
Matrix(const Matrix& x) :rows(x.rows), cols(x.cols) {
ptr = new int[rows * cols];
int* tmp = ptr; // HERE
mem += (rows * cols) * sizeof(int);
for (int i = 0; i < x.rows * x.cols; i++) {
ptr[i] = x.ptr[i];
}
}
~Matrix() {
mem -= (rows * cols) * sizeof(int);
delete[] ptr;
}
friend istream& operator>>(istream& input, Matrix& x) {
int* tmp = x.ptr;
for (int i = 0; i < x.rows; i++) {
for (int j = 0; j < x.cols; j++) {
input >> *tmp; tmp++;
}
}
return input;
}
friend ostream& operator<<(ostream& output, Matrix& x) {
int* tmp = x.ptr;
for (int i = 0; i < x.rows; i++) {
for (int j = 0; j < x.cols; j++) {
output << *tmp << " "; tmp++;
}
output << endl;
}
return output;
}
friend Matrix operator+(const Matrix& x, const Matrix& y) {
Matrix tmp(x.rows,x.cols);
if (x.rows != y.rows || x.cols != y.cols) {
return tmp;
}
else {
for (int i = 0; i < x.rows * x.cols; i++) {
tmp.ptr[i] = x.ptr[i] + y.ptr[i];
}
return tmp;
}
}
Matrix operator=(const Matrix& x) {
if (x.rows != x.cols) {
delete[] ptr;
rows = x.rows;
cols = x.cols;
ptr = new int[rows * cols];
mem += (rows * cols) * sizeof(int);
}
for (int i = 0; i < x.rows * x.cols; i++) {
ptr[i] = x.ptr[i];
}
return *this;
}
friend Matrix operator*(const Matrix& x, const Matrix& y) {...}
};
基于这段代码,我们必须重载 '*' 运算符,它将两个矩阵相乘(例如 C = A * B)。当使用 2D 数组相当容易时,我只是无法理解它现在的工作方式,所以任何帮助都将不胜感激。
谢谢你的时间!
解决方案
推荐阅读
- python - 处理 Django Util Timezone Ambiguous Time Error 而不直接修改 Django 包
- php - PHP Form Mail不发送电子邮件,给出一个空白页面,没有错误消息
- javascript - 如何使用 Javascript 在 CSS 中动态设置背景图片 url
- c# - 什么是 dropdownlist.selectedvalue?
- python - 如何从具有重复数据块的大文件中提取多个模式?
- bash - 来自 bash CLI 的 InfluxDB 查询
- flutter - [flutter]我无法在 Paint 中使用 BlendMode.srcIn
- matrix - 如何使用 sympy 执行向量乘法矩阵?
- python - Python 请求库无法解析非权威的 dns 查找
- fiware - Fiware orion 订阅发送空体