参数 1 没有从 'Traffic_light' 到 'Traffic_light&' 的已知转换
no known conversion for argument 1 from 'Traffic_light' to 'Traffic_light&'
我正在尝试"C++编程语言"一书中的一个例子。还有一个运算符定义的示例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
怎么了?
你应该坚持使用运算符++的常见实现,即
// 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;
}
但是由于您想临时调用预递增运算符,即
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