2013-08-03 69 views
1

對於學校我必須寫一個議程,它保存有關考試,任務數據和講座C程序設計:訪問枚舉值

我無法在我的結構訪問一個枚舉。

我的結構如下所示:

struct Item{ 

enum {TASK, EXAM, LECTURE} entryType; 

char* name; 
char* course; 

time_t start; 
time_t end; 

union 
{ 
    struct Task* task; 
    struct Exam* exam; 
    struct Lecture* lecture; 
} typeData; 
}; 

現在我用我的枚舉設置的項目類型。 該結構在Item.h中定義。 在Item.c包括Item.h我使用以下代碼:

struct Item* createItem(char* type){ 
struct Item* newItem; 

newItem = (struct Item *) malloc (sizeof(struct Item)); 

if (strcmp(type, "Task") == 0) 
{ 
    //newItem->entryType = newItem->TASK; 
    newItem->typeData.task = createTask(); 
} else if (strcmp(type, "Exam") == 0) 
{ 
    //newItem->entryType = newItem->EXAM; 
    newItem->typeData.exam = createExam(); 
} else if (strcmp(type, "Lecture") == 0) 
{ 
    //newItem->entryType = newItem->LECTURE; 
    newItem->typeData.lecture = createLecture(); 
} 

return newItem; 
} 

的註釋的代碼給我的錯誤(TASK例如):

錯誤C2039: '任務':不'Item'的成員

+0

'TASK'不是'任務'。 – 2013-08-03 14:46:32

+0

你在做什麼字符串比較?如果你使用的是枚舉,沒有理由使用'strcmp'。枚舉成員就像整數一樣工作。 –

+1

另外,[不要強制轉換'malloc()']的返回值(http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858)。 – 2013-08-03 14:47:51

回答

2

我的第一點是不必要的,其次是將createItem的參數更改爲int,第三是您在dataType中使用指針,所以我們真的應該看到這些函數,第四,在您的結構中創建一個int字段類型。

struct Item* createItem(int type){ 
    struct Item* newItem; 

    newItem = malloc (sizeof(struct Item));  

    newItem->entryType = type; 

    if (type == 0) 
    { 
    newItem->typeData.task = createTask(); 
    } else if (type == 1) 
    { 
    newItem->typeData.exam = createExam(); 
    } else if (type == 2) 
    { 
    newItem->typeData.lecture = createLecture(); 
    } 

return newItem; 
} 
+0

感謝您使用該類型的整數提示,我會看到這一點。而typeData函數不會給我任何錯誤,它們工作,所以我沒有看到給它們代碼的理由。但問題出在我們的分配上,我們已經得到了Item結構,並且我完全複製了它。沒有辦法做到這一點沒有使枚舉全球? – crognar

+0

@crognar你可以使用int來訪問枚舉的值。所以任何int和entryType都是可以互換的。 –

+0

@crognar現在的代碼不需要全局枚舉。 –

2

當你聲明的enum,其內容基本上已經成爲編譯時間常數,就好像你#defineð他們。特別是,如果您有enum { A, B, C } foo,您可以按照您的想法訪問選項A,而不是foo->A

+0

那麼如何訪問枚舉Name1 {Value2 = 0x1;}?就像我使用的代碼需要能夠從0x1中選擇值名稱,而不是Value2;就像你在課堂上一樣 – MarcusJ