首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >参数%1从“Traffic_light”到“Traffic_light&”的转换未知

参数%1从“Traffic_light”到“Traffic_light&”的转换未知
EN

Stack Overflow用户
提问于 2014-12-29 23:01:31
回答 1查看 463关注 0票数 1

我正在尝试“C++编程语言”这本书中的一个例子。这里有一个enum运算符定义的例子。

代码语言:javascript
复制
#include <iostream>

using namespace std;

enum Traffic_light {
    green,
    yellow,
    red
};

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

int main()
{   
    Traffic_light next = ++Traffic_light::yellow;
    return 0;
}

但是,当我尝试编译它时,我得到了一个错误

代码语言:javascript
复制
main.cpp: In function 'int main()':
main.cpp:22:23: error: no match for 'operator++' (operand type is 'Traffic_light')
  Traffic_light next = ++Traffic_light::yellow;
                       ^
main.cpp:22:23: note: candidate is:
main.cpp:11:16: note: Traffic_light& operator++(Traffic_light&)
 Traffic_light& operator++(Traffic_light& t)
                ^
main.cpp:11:16: note:   no known conversion for argument 1 from 'Traffic_light' to 'Traffic_light&'

我在cmd中使用以下命令编译它

代码语言:javascript
复制
g++ main.cpp -o main.exe --std=c++11

有什么问题吗?

EN

回答 1

Stack Overflow用户

发布于 2014-12-30 01:57:55

您应该坚持使用operator++的常见实现,即

代码语言:javascript
复制
// preincrementation
Enum& operator++( Enum &c ) {
  // do incrementation logic
  return *this;
}

// postincrementation
Enum operator++( Enum &e, int ) {
  Enum old = e;  // copy old state
  ++e;           // increment in therms of preincrement
  return old;
}

但是由于您想要在临时的、即

代码语言:javascript
复制
Traffic_light next = ++Traffic_light::yellow;

然后,您必须与此模式不同,并且您可能希望这样编写operator++:

代码语言:javascript
复制
#include <iostream>

enum Traffic_light { green, yellow, red, END};

Traffic_light operator++( Traffic_light t)
{
    // increment
    t = static_cast< Traffic_light>( static_cast<int>(t) + 1 );

    // wrap if out of range
    if ( t == Traffic_light::END )
        t = static_cast< Traffic_light> (0);

    return t;
};

Traffic_light operator++( Traffic_light l, int)
{
    Traffic_light t = l;
    ++l;
    return t;
};

int main()
{   
    Traffic_light nextPre = ++Traffic_light::yellow;
    std::cout << nextPre; // prints 1

    Traffic_light nextPost = Traffic_light::yellow++;
    std::cout << nextPost; // prints 2

    return 0;
}

http://ideone.com/Ixm7ax

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27691196

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档