我正在尝试“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有什么问题吗?
发布于 2014-12-30 01:57:55
您应该坚持使用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;
}但是由于您想要在临时的、即
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
https://stackoverflow.com/questions/27691196
复制相似问题