C++日期类与运算符的重载

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,针对您的问题,我可以给出以下代码示例: ```cpp #include <iostream> #include <vector> using namespace std; class Matrix { private: int row, col; vector<vector<int>> data; public: Matrix(int r, int c) : row(r), col(c), data(r, vector<int>(c)) {} Matrix operator+(const Matrix& other) const { if (row != other.row || col != other.col) { throw runtime_error("Matrix dimensions do not match."); } Matrix res(row, col); for (int i = 0; i < row; ++i) { for (int j = 0; j < col; ++j) { res.data[i][j] = data[i][j] + other.data[i][j]; } } return res; } Matrix operator-(const Matrix& other) const { if (row != other.row || col != other.col) { throw runtime_error("Matrix dimensions do not match."); } Matrix res(row, col); for (int i = 0; i < row; ++i) { for (int j = 0; j < col; ++j) { res.data[i][j] = data[i][j] - other.data[i][j]; } } return res; } Matrix operator*(const Matrix& other) const { if (col != other.row) { throw runtime_error("Matrix dimensions do not match."); } Matrix res(row, other.col); for (int i = 0; i < row; ++i) { for (int j = 0; j < other.col; ++j) { for (int k = 0; k < col; ++k) { res.data[i][j] += data[i][k] * other.data[k][j]; } } } return res; } friend ostream& operator<<(ostream& os, const Matrix& mat) { for (int i = 0; i < mat.row; ++i) { for (int j = 0; j < mat.col; ++j) { os << mat.data[i][j] << " "; } os << endl; } return os; } friend istream& operator>>(istream& is, Matrix& mat) { for (int i = 0; i < mat.row; ++i) { for (int j = 0; j < mat.col; ++j) { is >> mat.data[i][j]; } } return is; } }; int main() { Matrix A(2, 3), B(3, 2); cin >> A >> B; cout << A * B << endl; return 0; } ``` 这是一个简单的矩阵类,支持加、减、乘运算符重载。其中,加、减运算符要求两个矩阵的维度相同,乘运算符要求左矩阵的列数等于右矩阵的行数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值