12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- #include <iostream>
- #include <iomanip>
- class Matrix {
- private:
- int data[2][3];
- public:
- // 默认构造函数,初始化矩阵为0
- Matrix() {
- for (int i = 0; i < 2; ++i)
- for (int j = 0; j < 3; ++j)
- data[i][j] = 0;
- }
- // 重载输入运算符
- friend std::istream& operator>>(std::istream& in, Matrix& matrix) {
- for (int i = 0; i < 2; ++i) {
- for (int j = 0; j < 3; ++j) {
- in >> matrix.data[i][j];
- }
- }
- return in;
- }
- // 重载输出运算符
- friend std::ostream& operator<<(std::ostream& out, const Matrix& matrix) {
- for (int i = 0; i < 2; ++i) {
- for (int j = 0; j < 3; ++j) {
- out << std::setw(7) << matrix.data[i][j]; // 用这个什么setw设置宽度
- }
- out << std::endl;
- }
- return out;
- }
- // 重载加法运算符
- Matrix operator+(const Matrix& other) const {
- Matrix result;
- for (int i = 0; i < 2; ++i) {
- for (int j = 0; j < 3; ++j) {
- result.data[i][j] = this->data[i][j] + other.data[i][j];
- }
- }
- return result;
- }
- // 重载减法运算符
- Matrix operator-(const Matrix& other) const {
- Matrix result;
- for (int i = 0; i < 2; ++i) {
- for (int j = 0; j < 3; ++j) {
- result.data[i][j] = this->data[i][j] - other.data[i][j];
- }
- }
- return result;
- }
- };
- int main() {
- Matrix m1, m2;
- std::cout << "请输入2行3列矩阵内容:" << std::endl;
- std::cin >> m1;
- std::cout << "请输入2行3列矩阵内容:" << std::endl;
- std::cin >> m2;
- Matrix sum = m1 + m2;
- Matrix diff = m1 - m2;
- std::cout << "m1+m2=" << std::endl;
- std::cout << sum;
- std::cout << "m1-m2=" << std::endl;
- std::cout << diff;
- return 0;
- }
|