Operator Overloading(Important)

Hi, guys, trying to understand operator overloading, and i wrote some code just to define a "-" operator to do a simple subtraction. SO, i wrote a program that can perform a subtraction between two objects and put the result in the third object. now I Just cant show the result on the console.Can any one help? And also can anyone define the meaning of [b1.x], like I want to know am I assigning the value to the "b1"object or the x variable?
This is a very concept that I need to understand.Any help would be highly appreciated.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

#include<iostream>

using namespace std;

struct Ok
{
  int x;
  
  int y;
  
};


Ok operator-(const Ok& a , const Ok& b)

{
  Ok result;
  
  result = (a - b);

  return result;

}

int main()


{
  Ok b1;
  
  Ok b2;
  
  Ok b3;

 
 b1.x = 4;
 
 b2.y = 3;
 
 b3 = b1 - b2;
 
cout<<b3<<endl;  //doesnt work

}

Line 20 is your problem. Imagine renaming your operator function to "subtract". It would look like this:
1
2
3
4
5
OK subtract(const OK& a, const OK& b){
   Ok result;
   result = subtract(a, b);
   return result;
}


You've gone into infinite recursion with no way to break out. Write methods explicitly to modify the data members, like result.x = a.x - b.x;.
Thank you very much:)
Topic archived. No new replies allowed.