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!