要将一个整数数组转换为矩阵类并实现运算符重载,首先需要定义一个矩阵类,然后在该类中实现运算符重载。以下是一个简单的示例,展示了如何实现这一功能:
#include <vector>
#include <iostream>
class Matrix {
private:
std::vector<std::vector<int>> data;
int rows, cols;
public:
// 构造函数,接受一个整数数组和矩阵的维度
Matrix(const std::vector<int>& arr, int rows, int cols) : rows(rows), cols(cols) {
data.resize(rows, std::vector<int>(cols));
for (int i = 0; i < rows * cols; ++i) {
data[i / cols][i % cols] = arr[i];
}
}
// 获取矩阵的行数
int getRows() const { return rows; }
// 获取矩阵的列数
int getCols() const { return cols; }
// 重载加法运算符
Matrix operator+(const Matrix& other) const {
if (rows != other.rows || cols != other.cols) {
throw std::invalid_argument("Matrix dimensions must match for addition.");
}
Matrix result(data, rows, cols);
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
result.data[i][j] += other.data[i][j];
}
}
return result;
}
// 打印矩阵
void print() const {
for (const auto& row : data) {
for (int val : row) {
std::cout << val << " ";
}
std::cout << std::endl;
}
}
};
int main() {
std::vector<int> arr = {1, 2, 3, 4, 5, 6};
Matrix m1(arr, 2, 3);
Matrix m2(arr, 2, 3);
Matrix sum = m1 + m2;
sum.print();
return 0;
}
Matrix
类包含一个二维向量data
来存储矩阵的数据,以及rows
和cols
来表示矩阵的维度。+
,使得两个矩阵可以相加。如果两个矩阵的维度不匹配,则抛出异常。通过这种方式,你可以将整数数组转换为矩阵类,并实现基本的运算符重载,从而方便地进行矩阵运算。
没有搜到相关的沙龙