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

后端 未结 3 835
终归单人心
终归单人心 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 07:58

    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.

    0 讨论(0)
  • 2021-01-24 08:07

    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.

    0 讨论(0)
  • 2021-01-24 08:11

    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;
    }
    
    0 讨论(0)
提交回复
热议问题