I\'m working through Bjarne Stroustrup\'s The C++ Programming Language and I\'m stuck on one of the examples. Here\'s the code, and aside from whitespace differences and comment
You have a couple of problems:
First, you are attempting to implement a function (operator++
) inside another function (main
). C++ does not allow this (with the exception of lambdas).
Second, you are only implementing a prefix increment, so ++light
will work, but light++
will not. You should implement them both. An example of it can be found here.
Traffic_light& operator++(Traffic_light& t) is a function with name operator ++. Each function shall be defined outside any other function. So place the definition of the operator before main.
Here you have your code running:
http://coliru.stacked-crooked.com/a/74c0cbc5a8c48e47
#include <iostream>
#include <string>
#include <vector>
enum class Traffic_light {
green,
yellow,
red
};
Traffic_light & operator++(Traffic_light & t) {
switch (t) {
case Traffic_light::green:
t = Traffic_light::yellow;
break;
case Traffic_light::yellow:
t = Traffic_light::red;
break;
case Traffic_light::red:
t = Traffic_light::green;
break;
}
return t;
}
std::ostream& operator<<(std::ostream& os, Traffic_light & t)
{
switch(t)
{
case Traffic_light::green:
os << "green";
break;
case Traffic_light::yellow:
os << "yellow";
break;
case Traffic_light::red:
os << "red";
break;
}
return os;
}
int main()
{
Traffic_light light = Traffic_light::red;
std::cout << "Ligth:" << ++light << std::endl;
std::cout << "Ligth:" << ++light << std::endl;
std::cout << "Ligth:" << ++light << std::endl;
return 0;
}