定义一个描述矩阵的类Array,其数据成员为二维实型数组a【3】【3】,用Put成员函数为a【3】【3】输入元素值,重载+运算符完成两个数组的加法运算。分别用成员函数与友元函数编写运算符重载函数,用print成员函数输出a[3][3]的元素值。在主函数中用类Array定义对象a1,a2,啊3,调用put函数为a1与a2的数据成员输入元素值,进行加法a3=a1+a2的运算,并输出a1,a2,a3的全部元素值
时间: 2024-02-26 08:58:45 浏览: 27
好的,我理解了你的问题。下面是对应的C++代码实现:
```c++
#include<iostream>
using namespace std;
class Array{
private:
double a[3][3];
public:
void Put(){
cout << "请输入9个double类型的数:" << 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;
}
}
friend Array operator+(const Array& a1,const Array& a2){
Array res;
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
res.a[i][j] = a1.a[i][j] + a2.a[i][j];
}
}
return res;
}
Array operator+(const Array& other){
Array res;
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
res.a[i][j] = this->a[i][j] + other.a[i][j];
}
}
return res;
}
};
int main(){
Array a1,a2,a3;
a1.Put();
a1.print();
a2.Put();
a2.print();
a3 = a1 + a2;
a3.print();
return 0;
}
```
在这段代码中,我们定义了一个`Array`类,其中包含了矩阵的元素值`a[3][3]`,并且定义了`Put`函数,用于输入元素值,`print`函数用于输出元素值。我们重载了`+`运算符,既定义了类内的成员函数重载,也定义了友元函数重载,用于完成两个矩阵的加法运算。
在主函数中,我们定义了三个`Array`类的对象`a1`、`a2`、`a3`,用`Put`函数为`a1`和`a2`输入元素值,用`print`函数输出它们的元素值。然后,我们用`a3 = a1 + a2`完成了两个矩阵的加法运算,并用`print`函数输出了它们的元素值。
希望这个例子对你有所帮助!如果你有其他问题,可以继续向我提问。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)