Can#39;t define ++ operator in C++, what#39;s the issue here?(无法在 C++ 中定义 ++ 运算符,这里有什么问题?)
问题描述
我正在研究 Bjarne Stroustrup 的《C++ 编程语言》,但我被困在其中一个示例上.这是代码,除了空格差异和注释之外,我的代码与书中的代码相同(第 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;
}
然而,当我在 Mac OS X 10.9 上使用 clang++ -std=c++11 -stdlib=libc++ -Weverything main.cpp 编译它时,出现以下错误:
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
}
^
;
真正的障碍是 expected expression 错误,但 expected ; 也是有问题的.我做了什么?
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++ 中定义 ++ 运算符,这里有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法在 C++ 中定义 ++ 运算符,这里有什么问题?
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
