Can't define ++ operator in C++, what's the issue here?

后端 未结 3 841
终归单人心
终归单人心 2021-01-24 07:30

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

3条回答
  •  面向向阳花
    2021-01-24 08:11

    Here you have your code running:

    http://coliru.stacked-crooked.com/a/74c0cbc5a8c48e47

    #include 
    #include 
    #include 
    
    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;
    }
    

提交回复
热议问题