首页 新闻 赞助 找找看

C++重载运算符=

1
[已解决问题] 解决于 2020-04-29 20:49
 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class Matrix
 6 {
 7     private:
 8         int a,b;
 9         int arr[100][100];
10     public:
11         Matrix()
12         {
13             for(int i=0;i<100;i++)
14             {
15                 for(int j=0;j<100;j++)
16                 {
17                     arr[i][j]=0;
18                 }
19             }
20         }
21         void Gethl(int a, int b){this->a=a;this->b=b;}
22         void Getnum()
23         {
24             for(int i=0;i<a;i++)
25             {
26                 for(int j=0;j<b;j++)
27                 {
28                     cin>>arr[i][j];
29                 }
30             }
31         }
32         Matrix operator+(Matrix &c)
33         {
34             Matrix temp;
35             for(int i=0;i<a;i++)
36             {
37                 for(int j=0;j<b;j++)
38                 {
39                     temp.arr[i][j]=this->arr[i][j]+c.arr[i][j];
40                 }
41             }
42             return temp;
43         }
44         Matrix operator=(Matrix &c)
45         {
46               for(int i=0;i<a;i++)
47             {
48                 for(int j=0;j<b;j++)
49                 {
50                     arr[i][j]=c.arr[i][j];
51                 }
52             }
53         }
54         void show()
55         {
56             for(int i=0;i<a;i++)
57             {
58                 for(int j=0;j<b;j++)
59                 {
60                     if(j!=0)    cout<<" "<<arr[i][j];
61                     else    cout<<arr[i][j];
62                     if(j==b-1)  cout<<endl;
63                 }
64             }
65         }
66 };
67 
68 int main()
69 {
70     int a,b;
71     cin>>a>>b;
72     Matrix one,two,three;
73     one.Gethl(a,b);
74     two.Gethl(a,b);
75     one.Getnum();
76     two.Getnum();
77     three=one+two;
78     three.show();
79     return 0;
80 }

编译的时候会出错,

[Error] no match for 'operator=' (operand types are 'Matrix' and 'Matrix')

啥问题?

Conan-jine的主页 Conan-jine | 小虾三级 | 园豆:1272
提问于:2020-04-29 11:58

你重载了=,要求左边为值,右边为引用。但是你这里=两边都是值。

。淑女范erり 3年前

@。淑女范erり: 那我需要怎么写呢?我这会新学的没怎么明白,就试着做题了,毕竟做题才能更好的理解知识

Conan-jine 3年前

@。淑女范erり: 网上搜的那些没讲不明白或者我看不懂

Conan-jine 3年前

@Conan-jine: 重载运算符,没有特殊需要的话,最好返回引用。多问一句,你这是在自学C++吗。。

。淑女范erり 3年前

@。淑女范erり: 原本是自学的,结果这学期学院开课了,不过还是习惯自己的节奏,自己捣鼓,实在不懂了再麻烦老师

Conan-jine 3年前

@。淑女范erり: 我找到问题了,是因为我重载了两个运算符,一个+,一个=,但是+的返回值和=的参数类型不一样,导致 a=b+c不能运行,而a=b却可以,谢谢你,你别在评论里说话了,选择回复呀,我给你最佳答案

Conan-jine 3年前

@Conan-jine: 回了,(#.#)

。淑女范erり 3年前
< >
分享
最佳答案
1

你说的是对的,你重载的+,返回值是一个值,但是你重载的=,要求右值是引用,导致冲突了。

奖励园豆:5
。淑女范erり | 小虾三级 |园豆:961 | 2020-04-29 20:45
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册