首页 文章

将枚举传递给C中的函数

提问于
浏览
0

我有一个头文件,列出了所有的枚举(#ifndef #define #endif构造用于避免多次包含该文件),我在我的应用程序中的多个cpp文件中使用 . 文件中的一个枚举是

enum StatusSubsystem {ENABLED,INCORRECT_FRAME,INVALID_DATA,DISABLED};

应用程序中有一些功能被视为

ShowStatus(const StatusSubsystem&);

在应用程序早期我调用上面的函数时就像

ShowStatus(INCORRECT_FRAME);

我的应用程序用于编译完美 . 但是在添加了一些代码后,编译停止会发出以下错误:

File.cpp:71: error: invalid conversion from `int' to `StatusSubsystem'
File.cpp:71: error:   initializing argument 1 of `void Class::ShowStatus(const StatusSubsystem&)

我检查了代码中新代码中任何冲突的枚举,看起来很好 .

我的问题是编译器显示为错误的函数调用有什么问题?

供您参考,函数定义是:

void Class::ShowStatus(const StatusSubsystem& eStatus)
{

   QPalette palette;
   mStatus=eStatus;//store current Communication status of system 
   if(eStatus==DISABLED)
   {
     //select red color for  label, if it is to be shown disabled
     palette.setColor(QPalette::Window,QColor(Qt::red));
     mLabel->setText("SYSTEM");

   }
   else if(eStatus==ENABLED)
   {
      //select green color for label,if it is to be shown enabled
      palette.setColor(QPalette::Window,QColor(Qt::green));
     mLabel->setText("SYSTEM");

   }
   else if(eStatus==INCORRECT_FRAME)
   {
      //select yellow color for  label,to show that it is sending incorrect frames
      palette.setColor(QPalette::Window,QColor(Qt::yellow));
      mLabel->setText("SYSTEM(I)");

   }
   //Set the color on the  Label
   mLabel->setPalette(palette);
}

这种情况的一个奇怪的副作用是当我将所有调用转换为ShowStatus()时编译

ShowStatus((StatusSubsystem)INCORRECT_FRAME);

虽然这可以消除任何编译错误,但是会发生奇怪的事情 . 虽然我上面调用了INCORRECT_FRAME但是在函数定义中它与ENABLED匹配 . 这怎么可能呢?它就像通过引用传递INCORRECT_FRAME一样,它神奇地转换为ENABLED,这应该是不可能的 . 这让我疯了 .

你能找到我正在做的任何瑕疵吗?或者是别的什么?

该应用程序使用RHEL4上的C,Qt-4.2.1进行 .

谢谢 .

1 回答

  • 6

    你应该通过值来获取枚举,而不是通过const引用 . 它足够小以适应 int ,所以没有性能损失或类似的东西 .

    但是,从你所描述的内容来看,听起来有人在其他地方有一个0到14 . 你应该在它上面的行中添加如下内容:

    #ifdef INCORRECT_FRAME
    #error Whoops, INCORRECT_FRAME already defined!
    #endif
    

    顺便说一句, #ifndef thingy(对于你的头文件)被称为include guard . :-)

相关问题