-3

I was trying exercise on programmr.com. but I didn't get below example of basic operator overloading. can somebody please explain me below. challenge is:- "Overload the + operator for the class 'temp' to add and return the answer of two objects of class 'temp'."

   #include <iostream>

using namespace std;

class temp
{
  int value;

public:
  temp(int v=0) : value(v) { }

  //WRITE YOUR CODE HERE



  //

  int getVal()
  {
      return value;
  }
};

int main()
{
    int n1, n2;
    cout << "Enter value for t1: ";
    cin >> n1;
    cout << "Enter value for t2: ";
    cin >> n2;
    temp t1(n1), t2(n2), t3;
    t3 = t1+t2;
    cout << "Their sum is " << t3.getVal();
    return 0;
    }
Arun A S
  • 6,421
  • 4
  • 29
  • 43
Preet Singh
  • 75
  • 2
  • 10
  • 2
    what did you try, and why did it not work? – sp2danny Mar 28 '15 at 09:01
  • " //WRITE YOUR CODE HERE" ? We don't just write codes for you. Show what you tried. That way, we will also be able to understand how much you know about it. – Arun A S Mar 28 '15 at 09:06
  • Arun i am not telling to you guys for "//WRITE CODE HERE". That's exercise from programmr.com. they are saying that your code should be there. I am newbie in programming. i didn't understand above code that's what make me to post it here. Thanks – Preet Singh Mar 28 '15 at 09:22

1 Answers1

0

Firts of all it is better to declare member function getVal with qualifier const

  int getVal() const
  {
      return value;
  }

The operator can look like

temp operator +( const temp &t1, const temp &t2 )
{
    return temp( t1.getVal() + t2.getVal() );
}

or

const temp operator +( const temp &t1, const temp &t2 )
{
    return temp( t1.getVal() + t2.getVal() );
}

or

const temp operator +( const temp &t1, const temp &t2 )
{
    return { t1.getVal() + t2.getVal() };
}

or

const temp operator +( const temp &t1, const temp &t2 )
{
    return t1.getVal() + t2.getVal();
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335