Let's look at what you have so far:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
#include <iostream>
using namespace std;
Class Light
{
private:
public:
}
Light::Light()
{
}
Light::chgColor()
{
}
int main()
{
}
|
I'm assuming that this was what either you were given, or what you came up with so there isn't much to work with. Since I don't know the knowledge you have so far in this class, it's a little hard to say exactly what you know or the best route, but I'll go the simplest route and use booleans.
You have your constructor
Light::Light()
which is good and you already have a function for your class too
Light::chgColor()
which is also good. The problems that I see is that you're not using any variables in your class and therefore aren't storing an information in any objects. To get started, let's make some:
1 2
|
// We need variables to hold our colors
bool mRed, mYellow, mGreen;
|
Those will be true if the light is that color, false otherwise. They should be private. Now, instructions say to make the constructor make a red light, which is simple, we just make all of the colors false, except for red.
1 2 3 4
|
Light::Light() :
mRed(true), mYellow(false), mGreen(false) {
// We don't need to do anything else in here, so it's left blank
}
|
Now, to change color:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
void Light::chgColor() {
// See if the light is red
if (mGreen) {
// Set it to false
mGreen = false;
// And make it yellow
mYellow = true;
}
// We need else ifs or the light will be green each time
else if (mYellow) {
mYellow = false;
mRed = true;
}
// Assume it's red
else {
mRed = false;
mGreen = true;
}
}
|
That was simple, messy, but simple. Now, let's have a way to have the object tell you which color it is:
1 2 3 4 5 6 7 8
|
string Light::getColor() {
if (mGreen)
return "Green";
else if (mYellow)
return "Yellow";
else
return "Red";
}
|
And that should be all you need.
Now, a word of caution. Your teacher already knows about this site and I'm sure she checks it regularly for students asking for help so she will know that you used someone else's code. Meaning, do not use this code and turn it in as your own because you will get a zero on it. There are plenty of things that can be changed to make this your own including using ints instead of booleans (you should only need one int), using an enum (again, only need one) or whatever else you seem fit.
There are header files missing and I didn't give you a complete class example so that you have to work to get it to work together nicely.
Note: Only constructors (ctors) and destructors (dtors) don't have data types. All other class functions require a data type (including those that return nothing) in order to be valid code. Any questions, and I'll surely help.