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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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
Thanks for your registration, follow us on our social networks to keep up-to-date