So I'm trying to learn programming on my own and I'm sort of stuck on overloading increment operators. I don't understand how the compiler can distinguish between which member function to use in the given example (from a book I'm reading):
Quote
#include <iostream>
using namespace std;
#include <string>
typedef unsigned short USHORT;
class Counter
{
public:
Counter();
~Counter(){}
USHORT GetItsVal()const { return itsVal; }
void SetItsVal(USHORT x) {itsVal = x; }
//const Counter& operator++ (); // prefix
const Counter operator++ (int); // postfix
private:
USHORT itsVal;
};
Counter::Counter():
itsVal(0)
{}
/*
const Counter& Counter::operator++()
{
++itsVal;
return *this;
}
*/
const Counter Counter::operator++(int)
{
Counter temp(*this);
++itsVal;
return temp;
}
int main() {
Counter i;
cout << "The value of i is " << i.GetItsVal() << endl;
i++;
cout << "The value of i is " << i.GetItsVal() << endl;
++i;
cout << "The value of i is " << i.GetItsVal() << endl;
Counter a = ++i;
cout << "The value of a: " << a.GetItsVal();
cout << " and i: " << i.GetItsVal() << endl;
a = i++;
cout << "The value of a: " << a.GetItsVal();
cout << " and i: " << i.GetItsVal() << endl;
system("PAUSE");
return 0;
}
using namespace std;
#include <string>
typedef unsigned short USHORT;
class Counter
{
public:
Counter();
~Counter(){}
USHORT GetItsVal()const { return itsVal; }
void SetItsVal(USHORT x) {itsVal = x; }
//const Counter& operator++ (); // prefix
const Counter operator++ (int); // postfix
private:
USHORT itsVal;
};
Counter::Counter():
itsVal(0)
{}
/*
const Counter& Counter::operator++()
{
++itsVal;
return *this;
}
*/
const Counter Counter::operator++(int)
{
Counter temp(*this);
++itsVal;
return temp;
}
int main() {
Counter i;
cout << "The value of i is " << i.GetItsVal() << endl;
i++;
cout << "The value of i is " << i.GetItsVal() << endl;
++i;
cout << "The value of i is " << i.GetItsVal() << endl;
Counter a = ++i;
cout << "The value of a: " << a.GetItsVal();
cout << " and i: " << i.GetItsVal() << endl;
a = i++;
cout << "The value of a: " << a.GetItsVal();
cout << " and i: " << i.GetItsVal() << endl;
system("PAUSE");
return 0;
}
Thanks in advance












