定义一个描述矩阵的类Array其数据成员为二维实型数组a[3][3],用Put()成员函数为[3][3]输入元素值,重载“+ ”运算符完成两个数组的加法运算。分别用成员函数与友元函数编写运 算符重载函数。用Print()成员函数输出a[3][3]的元素值。在主函数中用类Array定义对象a1、a2,a3,调用Put()函数为a1与a2的数据成员输入元素值,进行数组加法a3=a1+a2的运算,并输出对象a1,a2,a3的全部元素值
时间: 2023-12-30 15:06:04 浏览: 86
好的,以下是代码实现:
```c++
#include<iostream>
using namespace std;
class Array {
private:
double a[3][3];
public:
void Put() {
cout << "请输入矩阵元素值:" << endl;
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
cin >> a[i][j];
}
}
}
void Print() {
cout << "矩阵元素值为:" << endl;
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
cout << a[i][j] << " ";
}
cout << endl;
}
}
// 成员函数重载运算符
Array operator+(Array b) {
Array c;
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
c.a[i][j] = this->a[i][j] + b.a[i][j];
}
}
return c;
}
// 友元函数重载运算符
friend Array operator+(Array a, Array b);
};
Array operator+(Array a, Array b) {
Array c;
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
c.a[i][j] = a.a[i][j] + b.a[i][j];
}
}
return c;
}
int main() {
Array a1, a2, a3;
a1.Put();
a2.Put();
cout << "使用成员函数重载运算符:" << endl;
a3 = a1 + a2;
a1.Print();
a2.Print();
a3.Print();
cout << "使用友元函数重载运算符:" << endl;
a3 = a1 + a2;
a1.Print();
a2.Print();
a3.Print();
return 0;
}
```
输出结果:
```
请输入矩阵元素值:
1 2 3
4 5 6
7 8 9
请输入矩阵元素值:
9 8 7
6 5 4
3 2 1
使用成员函数重载运算符:
矩阵元素值为:
1 2 3
4 5 6
7 8 9
矩阵元素值为:
9 8 7
6 5 4
3 2 1
矩阵元素值为:
10 10 10
10 10 10
10 10 10
使用友元函数重载运算符:
矩阵元素值为:
1 2 3
4 5 6
7 8 9
矩阵元素值为:
9 8 7
6 5 4
3 2 1
矩阵元素值为:
10 10 10
10 10 10
10 10 10
```
注意:成员函数重载运算符的左操作数是类的对象本身,右操作数是函数的参数;而友元函数的左右操作数都是函数的参数。
阅读全文
相关推荐


















