簡體   English   中英

C ++中的SysRc枚舉值

[英]SysRc enum values in c c++

我正在一個項目中使用SysRc值作為SUCCESS和FAILURE ond sum enums之類的函數的返回值。 現在我想知道如何打印它們?

建立在尼爾的職位上:

在C ++中,通常使用switch語句使用枚舉值。 您可以使用#define -macros節省一些寫作工作,但我個人避免使用它們。

enum E  { foo, bar };
const char * ToStr( E e ) {
    switch(e) {
    case foo: return "foo";
    case bar: return "bar";
    };
    throw std::runtime_error("unhandled enum-value"); // xxx
}

gcc會警告您有關未處理的case值。

無法直接在C或C ++中執行此操作-您必須編寫將枚舉值作為參數並將其轉換為字符串的函數。

enum E  { foo, bar };

const char * ToStr( E e ) {
    if ( e == foo ) {
           return "foo";
    }
    else {
         return "bar";
     }
}

正如其他人所說,您無法列出枚舉名稱。 但是,您可以使用X-macros來生成枚舉和字符串數組:

在colours.h中:

#define COLOUR_VALUES \
    X(RED) \
    X(BLUE) \
    X(YELLOW)

#define X(a) a,
typedef enum {
   COLOUR_VALUES
} colour_t;
#undef X

extern char *colour_names[];

在colours.c中:

#include "colours.h"

#define X(a) #a,
char *colour_names[] = {
    COLOUR_VALUES
};
#undef X

void print_colour(colour_t colour)
{
     printf("%s\n", colour_names[colour]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM