programming operator +

Can I programme the operator + for new data types, like the below example?

1
2
3
4
5
6
7
8
9
10
11
12
typedef int pinax[4][4];

/*programe the + operator?*/

int main()
{
  ...
  pinax A,B,C;
  ...
  C=A+B;
  ...
};
Yes, you can. However, pinax is not a new data type.
Use a class to wrap the array.
How can I programme the operator in general?
You can only overload operators for classes/structs.

You'll have to objectify this:

1
2
3
4
5
6
7
8
9
10
11
12
class pinax
{
  // ... stuff to here

  pinax operator + (const pinax& r) const
  {
    pinax sum;
    //  add '*this' to 'r'   put result in 'sum'
    return sum;
  }
};
Hope this helps you...
This will show you how to make your own "<<" , "+" and "=" operator definitions.... other operators are also the same...
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
47
48
49
50
51
52
53
class point{
      public:
         // a point has 3 coordinates in space
          double x,y,z;        

        // the constructer, default pointer values are set to (0,0,0)
          point(double X=0,double Y=0,double Z=0){
                   x=X;
                   y=Y;
                   z=Z;
          }

        // adding two points together is
              // adding each correspondent coordinate
          point operator +(point &p){
                  point q;
                  q.x=p.x + x;
                  q.y=p.y + y;
                  q.z=p.z + z;
                  return q;
          }

       // when two points are made equal
           // correspondent coordinates will get equal
          point operator =(point &p){
                   x=p.x;
                   y=p.y;
                   z=p.z;
                   return *this;
          }
};

// when we want to print a point ( send it to cout) it should look
// like this :- ( x, y, z )
ostream &operator <<(ostream &stream, point &p){
       stream << "( " << p.x <<", "<< p.y <<", "<< p.z <<" )" ;
       return stream;
}

int main(){

point p(1,5);     // p( 1, 5, 0 )
point q(1.5, 2, -50);     //q( 1.5, 2, -50 )
point r;       // r( 0, 0, 0 )

cout << "r before addition : r" << r <<endl;

r = p + q;         //   r( 2.5, 7, -50 )

cout << "r after addition : r" << r <<endl;

return 0;
}
Last edited on
Thank you, this really helps.
Topic archived. No new replies allowed.