CFS1
CFS1

Reputation: 45

Operator Overloading with template

I am trying to modify the Add function to represent operator overloading.

#include <iostream>
using namespace std;

template <class T>
class cpair
{
public:
    cpair(T x = 0, T y = 0) { A = x; B = y; }
    void print()
    {
        cout << A << " " << B << endl;
    }
    T A, B;
};

template <class T>
void Add(cpair<T> A1, cpair<T> A2, cpair<T> &R)
{
    R.A = A1.A + A2.A;
    R.B = A1.B + A2.B;
}

int main()
{
    cpair<int> A1(4, 5), A2(1, 3), result;
    Add(A1, A2, result);
    result.print();

    return 0;
}

I am learning operator overloading, but I don't think I have implemented it correctly. The error I get is:

'operator= must be a member function'.

template <class T>
void operator=(const cpair<T> &A1, cpair<T> &A2, cpair<T> &R) { 
       R.A = A1.A + A2.A;
       R.B = A1.B + A2.B;
}

int main()
{
    cpair<int> A1(4, 5), A2(1, 3), result;
    operator(A1, A2, result);
    result.print();
}

How do you go about modifying the Add function to represent operator overloading and then call the function in Main? Thank you.

Upvotes: 1

Views: 141

Answers (2)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275210

template <class T>
class cpair {
public:
  cpair& operator+=( cpair const& o )&{
    A+=o.A;
    B+=o.B;
    return *this;
  }
  friend cpair operator+( cpair lhs, cpair const& rhs ){
    lhs+=rhs;
    return lhs;
  }
//...

the above is the canonical way to override + on a template class.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409136

You're misunderstanding quite a lot it seems. First of all if you want to overload the addition operator it's the operator+ function you need to overload, not the assignment operator.

To fix this you should do e.g.

template <class T>
cpair<T> operator+(cpair<T> const& a, cpair<T> const& b)
{
    return cpair<T>(a.A + b.A, a.B + b.B);
}

Secondly, if you overload an operator you can use it just like you would otherwise use it. For example, with e.g.

int a = 5, b = 7, r;

then you would do

r = a + b;

It's the same with your overloaded operators:

cpair<int> a(4, 5), b(1, 3), result;
result = a + b;

If you want to learn more I suggest you get a few good books to read.

Upvotes: 2

Related Questions