运算符重载有关编程题
时间: 2023-12-07 08:04:56 浏览: 61
运算符重载
以下是一个关于运算符重载的编程题:
定义一个矩阵类Matrix,包含私有成员变量int* ptr、int row、int column,分别表示矩阵的元素指针、行数、列数。请实现以下运算符重载:
1.重载()运算符,使得可以通过m(i,j)的方式访问矩阵中第i行第j列的元素,其中m为Matrix对象。
2.重载+运算符,使得可以对两个Matrix对象进行相加操作。
3.重载-运算符,使得可以对两个Matrix对象进行相减操作。
4.重载*运算符,使得可以对两个Matrix对象进行相乘操作。
5.重载=运算符,使得可以将一个Matrix对象赋值给另一个Matrix对象。
6.重载<<运算符,使得可以将Matrix对象以矩阵的形式输出到标准输出流中。
以下是一个示例程序,演示了如何使用Matrix类:
```cpp
#include <iostream>
using namespace std;
class Matrix {
private:
int* ptr;
int row;
int column;
public:
Matrix(int r, int c) : row(r), column(c) {
ptr = new int[r * c];
}
~Matrix() {
delete[] ptr;
}
int& operator()(int i, int j) {
return ptr[i * column + j];
}
Matrix operator+(const Matrix& m) const {
Matrix result(row, column);
for (int i = 0; i < row * column; i++) {
result.ptr[i] = ptr[i] + m.ptr[i];
}
return result;
}
Matrix operator-(const Matrix& m) const {
Matrix result(row, column);
for (int i = 0; i < row * column; i++) {
result.ptr[i] = ptr[i] - m.ptr[i];
}
return result;
}
Matrix operator*(const Matrix& m) const {
Matrix result(row, m.column);
for (int i = 0; i < row; i++) {
for (int j = 0; j < m.column; j++) {
int sum = 0;
for (int k = 0; k < column; k++) {
sum += (*this)(i, k) * m(k, j);
}
result(i, j) = sum;
}
}
return result;
}
Matrix& operator=(const Matrix& m) {
if (this != &m) {
delete[] ptr;
row = m.row;
column = m.column;
ptr = new int[row * column];
for (int i = 0; i < row * column; i++) {
ptr[i] = m.ptr[i];
}
}
return *this;
}
friend ostream& operator<<(ostream& os, const Matrix& m) {
for (int i = 0; i < m.row; i++) {
for (int j = 0; j < m.column; j++) {
os << m(i, j) << " ";
}
os << endl;
}
return os;
}
};
int main() {
Matrix m1(2, 3);
m1(0, 0) = 1;
m1(0, 1) = 2;
m1(0, 2) = 3;
m1(1, 0) = 4;
m1(1, 1) = 5;
m1(1, 2) = 6;
Matrix m2(2, 3);
m2(0, 0) = 7;
m2(0, 1) = 8;
m2(0, 2) = 9;
m2(1, 0) = 10;
m2(1, 1) = 11;
m2(1, 2) = 12;
Matrix m3 = m1 + m2;
cout << m3 << endl;
Matrix m4 = m1 - m2;
cout << m4 << endl;
Matrix m5(3, 2);
m5(0, 0) = 1;
m5(0, 1) = 2;
m5(1, 0) = 3;
m5(1, 1) = 4;
m5(2, 0) = 5;
m5(2, 1) = 6;
Matrix m6 = m1 * m5;
cout << m6 << endl;
Matrix m7(2, 3);
m7 = m1;
cout << m7 << endl;
return 0;
}
```
阅读全文