我先在windows下的VC++用c++语言写了一个测试枚举类型的程序,编译的时候出错了,后来我就写了一个很简单的c的程序,源代码如下:
(以下程序在linux下用gcc编译)
#include <stdio.h>
int main()
{
enum color {red,yellow,blue,white,black};
enum color i;
for(i = red;i <= black;i++)
{
printf("%d ",i);
}
return 0;
}
编译运行都没问题,我又把这个改成c++版的,源代码如下:
#include <iostream.h>
int main()
{
enum color {red,yellow,blue,white,black};
enum color i;
for(i = red;i <= black;i++)
{
cout << i << " ";
}
return 0;
}
用gcc编译的时候就出错了,错误如下:
[root@localhost enum]# gcc -c enum2.cpp
In file included from /usr/lib/gcc/i386-redhat-linux/4.0.0/../../../../include/c++/4.0.0/backward/iostream.h:31,
from enum2.cpp:1:
/usr/lib/gcc/i386-redhat-linux/4.0.0/../../../../include/c++/4.0.0/backward/backward_warning.h:32:2: warning: #warning This file includes at least one deprecated or antiquated header. Please consider using one of the 32 headers found in section 17.4.1.2 of the C++ standard. Examples include substituting the <X> header for the <X.h> header for C++ includes, or <iostream> instead of the deprecated header <iostream.h>. To disable this warning use -Wno-deprecated.
enum2.cpp: In function ‘int main()’:
enum2.cpp:8: 错误:no ‘operator++(int)’ declared for postfix ‘++’, trying prefix operator instead
enum2.cpp:8: 错误:no match 为 ‘operator++’ 在 ‘++i’ 中
解决方法:重写++操作符
#include <iostream>
using namespace std;
enum color {red,yellow,blue,white,black};
color& operator++(color& d)
{
return d = (black==d)?red:color(d+1) ;
}
int main()
{
color i;
for(i = red; i <= black; ++i)
{
cout << i << " ";
}
return 0;
}