c语言和c++的枚举操作有区别


我先在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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值