struct Bulb
{
// default constructor - set bulb state to off:
Bulb()
: level(off)
{
}
// custom constructor - set bulb state to argv[0]:
Bulb(constshort _level)
: level(_level)
{
}
enum Level
{
off,
dim,
bright
};
// increment instance : 0 to 1 to 2 to 0 ...
shortoperator ++ ()
{
level++;
if (level > bright)
level = off;
return level;
}
// decrement instance : 0 to 2 to 1 to 0 ...
shortoperator -- ()
{
level--;
if (level < off)
level = bright;
return level;
}
short level;
};
int main()
{
// declare an array of Bulb's:
Bulb bulbs[] = {Bulb::bright, Bulb::bright, Bulb::bright, Bulb::bright, Bulb::bright};
// we should have 5 Bulb's:
constint COUNT = sizeof(bulbs)/sizeof(Bulb);
// loop a number of times to change each state of a Bulb a few times:
for (int n = 0; n < 9; ++n)
for (int m = 0; m < COUNT; ++m) // iterate through array
bulbs[m]++; // increment each bulb : 0 to 1 to 2 to 0 to 1 to 2 to 0 ...
// return back to OS with no error:
return 0;
}
Hiya, it looks rather complex!!!
I have only learnt a little bit about classes, so could you comment some parts of the code pls?
Also, in main(), if I chose to turn bulb 2 to dim, when it is off, how would I do that ?
I have updated, code to add comments. HTH It is really quite simple, we have a struct that has a default constructor and a custom constructor. The struct has a single member variable 'level', and a ++ and -- operator so that each instance of a Bulb can be incremented/decremented. You previously had a if | else if | else construct to do the same as the ++ operator for a Bulb now does. Calling the increment operator ++ increments the Bulb::level through off | 0 to dim | 1 to bright | 2 then back through to off | 0 etc... this is what happens when you increment an integer through its entire range when you get to the upper bounds of an integer it will loop round ...