在C ++中无法定义++运算符,这里有什么问题? [英] Can't define ++ operator in C++, what's the issue here?
问题描述
我正在通过Bjarne Stroustrup的C ++编程语言,我坚持其中的一个例子。这里是代码,除了空白的差异和注释我的代码是相同的,在这本书(p.51)。
I'm working through Bjarne Stroustrup's The C++ Programming Language and I'm stuck on one of the examples. Here's the code, and aside from whitespace differences and comments my code is identical to what's in the book (p.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;
}
$ b < c ++ 11 -stdlib = libc ++ -Weverything main.cpp 在Mac OS X 10.9我得到以下错误:
Yet when I compile it with clang++ -std=c++11 -stdlib=libc++ -Weverything main.cpp
on Mac OS X 10.9 I get the following errors:
main.cpp:24:9: error: expected expression
switch (t) {
^
main.cpp:32:6: error: expected ';' at end of declaration
}
^
;
真正的障碍是预期表达式
错误,但预期;
也有问题。我做了什么?
The real baffeler is the expected expression
error, but the expected ;
is problematic as well. What have I done?
推荐答案
Traffic_light& operator ++(Traffic_light& t)是一个名为operator ++的函数。每个函数应在任何其他函数之外定义。所以把操作符的定义放在main之前。
Traffic_light& operator++(Traffic_light& t) is a function with name operator ++. Each function shall be defined outside any other function. So place the definition of the operator before main.
这篇关于在C ++中无法定义++运算符,这里有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!