I think your analysis may be over complicating the way it works. Sorry if my several posts led to that.
On each point:
u add one ctor for declare count to default value |
The 1st ctor is the one you already had:
Counter() : count(0){}
and then declare another ctor for returning x to oporeation function |
I added the 2nd ctor:
Counter(int x) : count(x){)
so that it is possible to convert an int value to a Counter object. It is needed if we want the post-fix operator to be defined like this:
1 2 3 4
|
Counter operator ++ (int)
{
return Counter(count++);// int ctor used here
}
|
However, if we do this instead:
1 2 3 4 5 6
|
Counter operator ++ (int)
{
Counter temp;// your original ctor used here
temp.count = count++;
return temp;
}
|
then the int ctor isn't needed at all.
About the post-fix operator. I threw that in there because you had asked about using a temp Counter variable in the ++ operator. A temp Counter variable is needed for the post-fix form, but not for the pre-fix form.
i think for doing postfix we have to add a argument for telling to compiler that we have integer before a operator |
I haven't ever seen a satisfying explanation for the int argument being used except that it is there to distinguish the function from the pre-fix one and it is just done that way. Note that no variable name is supplied with the argument as we never intend to actually use it.
To summarize, I have the following for your Counter class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
class Counter
{
private:
unsigned int count;
public:
Counter() : count(0){}
Counter(int x) : count(x){}// needed only for making the postfix ++ operator work
unsigned int get_count(){ return count; }
Counter& operator ++ ()// prefix
{
++count;
return *this;
}
Counter operator ++ (int)// postfix
{
return Counter(count++);// int ctor is used here
}
};
|
I hope this reply is helpful and did not make the confusion worse.