Loading... ```cpp #include<iostream> class Complex { private: double real; double imag; public: Complex() { real = 0; imag = 0; } Complex(double r, double i) { real = r; imag = i; } Complex operator+(const Complex& c2) { Complex c3; c3.real = real + c2.real; c3.imag = imag + c2.imag; return c3; } Complex operator+(const int& i) { Complex c3; c3.real = real + i; c3.imag = imag; return c3; } Complex operator+(const double& d) { Complex c3; c3.real = real + d; c3.imag = imag; return c3; } void display() { std::cout << real << " + " << imag << "i" << std::endl; } }; int main() { Complex c1(1,2), c2(3,4), c3; c3 = c1 + c2; std::cout << "c1 + c2 = "; c3.display(); c3 = c1 + 5; std::cout << "c1 + 5 = "; c3.display(); c3 = 3.14 + c1; std::cout << "3.14 + c1 = "; c3.display(); return 0; } ``` ```cpp #include<iostream> const int ROW = 3; const int COL = 3; class Matrix { private: int data[ROW][COL]; public: Matrix() { } Matrix(int d[][COL]) { for(int i=0; i<ROW; i++) { for(int j=0; j<COL; j++) { data[i][j] = d[i][j]; } } } Matrix operator+(const Matrix& m2) { Matrix m3; for(int i=0; i<ROW; i++) { for(int j=0; j<COL; j++) { m3.data[i][j] = data[i][j] + m2.data[i][j]; } } return m3; } Matrix operator-(const Matrix& m2) { Matrix m3; for(int i=0; i<ROW; i++) { for(int j=0; j<COL; j++) { m3.data[i][j] = data[i][j] - m2.data[i][j]; } } return m3; } void display() { for(int i=0; i<ROW; i++) { for(int j=0; j<COL; j++) { std::cout << data[i][j] << " "; } std::cout << std::endl; } } }; int main() { int d1[ROW][COL] = {{1,2,3},{4,5,6},{7,8,9}}; Matrix m1(d1); int d2[ROW][COL]; std::cout << "Enter elements of the second matrix:" << std::endl; for(int i=0; i<ROW; i++) { for(int j=0; j<COL; j++) { std::cin >> d2[i][j]; } } Matrix m2(d2); Matrix m3 = m1 + m2; std::cout << "m1 + m2 = " << std::endl; m3.display(); Matrix m4 = m1 - m2; std::cout << "m1 - m2 = " << std::endl; m4.display(); return 0; } ``` 最后修改:2023 年 08 月 05 日 © 允许规范转载 赞 2 如果觉得我的文章对你有用,请随意赞赏