Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
Jan 18, 2000

Overloading Operator

Question:
How do I overload the ++ operator to work with an enum variable? For example, I defined SuitType to be {Heat, Club, Diamond, Spade}. I want to use s++ (where s is a variable of SuitType) so that it will advance s from Hearts, to Clubs, to Diamonds, etc.

Answer:
I'll give an example of operator ++. Overloading operator ++ for an enum type consists of the following steps.

First you check whether the enum variable has the highest enumerator value. In that case, you perform a rollover by assigning the lowest enumerator value to it. Otherwise, you simply cast the enum variable to an int, increment it, cast that int back to the enum type, and return the result.

Here is a complete example of overloading ++ for the days of the week:

 
enum Days {Mon, Tue, Wed, Thur, Fri, Sat, Sun};
Days& operator ++ (Days& d) //overloaded operator
{
  if (d == Sun) 
    return d = Mon; //rollover
  int temp = d;
  ++temp;
  return d = static_cast (temp); 
}
int main()
{
 Days day = Mon;
 ++day;  // day now equals Tue
 return 0;
} 
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap