【问题标题】:Can't define ++ operator in C++, what's the issue here?无法在 C++ 中定义 ++ 运算符,这里有什么问题?
【发布时间】:2014-01-07 16:16:26
【问题描述】:

我正在研究 Bjarne Stroustrup 的《C++ 编程语言》,但我一直停留在其中一个示例上。这是代码,除了空格差异和 cmets 之外,我的代码与书中的代码相同(第 51 页)。

enum class Traffic_light { green, yellow, red};
int main(int argc, const char * argv[])
{
    Traffic_light light = Traffic_light::red;
//    DEFINING OPERATORS FOR ENUM CLASSES
//    enum classes don't have all the operators, must define them manually.
    Traffic_light& operator++(Traffic_light& t) {
        switch (t) {
            case Traffic_light::green:
                return t = Traffic_light::yellow;
            case Traffic_light::yellow:
                return t = Traffic_light::red;
            case Traffic_light::red:
                return t = Traffic_light::green;
        }
    }

    return 0;
}

然而,当我在 Mac OS X 10.9 上使用 clang++ -std=c++11 -stdlib=libc++ -Weverything main.cpp 编译它时,出现以下错误:

main.cpp:24:9: error: expected expression
        switch (t) {
        ^
main.cpp:32:6: error: expected ';' at end of declaration
    }
     ^
     ;

真正的障碍是expected expression 错误,但expected ; 也有问题。我做了什么?

【问题讨论】:

  • 您正试图在函数内部定义一个函数。你不能。
  • 只要在你的主函数之外做...

标签: c++ c++11 enums switch-statement operator-overloading


【解决方案1】:

Traffic_light& operator++(Traffic_light& t) 是一个名为 operator++ 的函数。每个功能都应在任何其他功能之外定义。所以把操作符的定义放在main之前。

【讨论】:

  • 这就是问题所在。谢谢。我已经习惯了像 JavaScript 这样的语言,你可以把函数放在你想要的任何地方。只要 StackOverflow 允许我,我就会接受答案。 (愚蠢的时间延迟)
【解决方案2】:

您的代码正在运行:

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

【讨论】:

    【解决方案3】:

    你有几个问题:

    首先,您尝试在另一个函数 (main) 中实现一个函数 (operator++)。 C++ 不允许这样做(lambda 除外)。

    其次,你只是实现了一个前缀增量,所以++light 可以工作,但light++ 不行。你应该同时实现它们。一个例子可以在here找到。

    【讨论】:

    • C/C++ 允许在另一个函数中声明一个函数。他们不允许定义函数。
    猜你喜欢
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多