0

I am currently practicing operator overloading regarding the increment operator ++, so I want to create a class myInt with just an integer m_Int and initialize it to zero.To distinguish pre & post increment, I created two overloading functions like below:

#include <iostream>
#include <string>
using namespace std;

class myInt 
{
    friend ostream & operator<<(ostream &cout, myInt &i);
    friend myInt & operator++(myInt &i);
public:
    myInt() 
    {
        m_Int = 0;
    }
    // post increment
    myInt operator++() 
    {
        myInt temp = *this;
        m_Int++;
        return temp;
    }
private:
    int m_Int;
};

ostream & operator<<(ostream &cout, myInt &i) 
{
    cout << "i.m_Int = " << i.m_Int;
    return cout;
}
// pre increment
myInt & operator++(myInt &i) 
{
    i.m_Int += 1;
    return i;
}
void test() 
{
    myInt int1;
    cout << int1 << endl;       // output ought to be 0 here
    cout << ++int1 << endl;     // having 1 here for prefix increment 
    cout << int1++ << endl;     // still 1 since its postfix increment
    cout << int1 << endl;       // 2 here thanks to postfix increment
}
int main() 
{
    test();
    system("pause");
    return 0;
}

So above is what I had in mind, based on my understanding, ++int1 == operator++(int1), and int1++ == int1.operator++(), so I choose to put one function inside the class, and another outside. But I got an error saying multiple functions matched both ++int1 and int1++, but these two do have different parameters, is it because one is defined inside the class and the other one is not, so parameter (myInt &i) doesn't make a difference here? Anyone has a clue if I got "++int1 == operator++(int1), and int1++ == int1.operator++()" part wrong? and how should I fix this to make it work? Much appreciated!

Larry1024
  • 11
  • 3
  • 4
    You misunderstand something. The *post*fix increment (and decrement) operator is called with an `int` argument. The *pre*fix operator have no argument. As member function the prefix operator is `myInt& operator++()`, and as non-member function it's `myInt& operator++(myInt const&)`. The postfix operator as a member function is `myInt operator++(int)`, and as a non-member function `myInt operator++(myInt const&, int)`. – Some programmer dude Sep 11 '20 at 08:50
  • Also see [this operator overload reference](https://en.cppreference.com/w/cpp/language/operators) (especially about [the increment/decrement operators](https://en.cppreference.com/w/cpp/language/operators#Increment_and_decrement)). I also recommend a [good book or two](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) as they should the information about this as well. – Some programmer dude Sep 11 '20 at 08:51
  • @Someprogrammerdude Thank you guys! Still confused about this part but I will try to figure it out with the references you gave! I think they would be really helpful! – Larry1024 Sep 11 '20 at 09:03

0 Answers0