没有来自' Traffic_light'的参数1的已知转换到' Traffic_light&'

时间:2014-12-29 15:01:31

标签: c++

我正在尝试一本书中的例子" The C ++ Programming Language"。还有一个enum运算符定义的例子。

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

然而,当我尝试编译它时,我遇到了错误

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

中使用此命令编译它
g++ main.cpp -o main.exe --std=c++11

问题是什么?

1 个答案:

答案 0 :(得分:0)

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

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

但是因为你想在临时调用preincrementation运算符,即

Traffic_light next = ++Traffic_light::yellow;

然后你必须偏离这种模式,你可能想用这种方式编写operator ++:

#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