枚舉

2009-12-04 136 views
0

轉換運營商,我寫的類是這樣的:枚舉

#pragma once 
#include "stdafx.h" 

struct Date 
{ 
private: 
int day; 
int year; 
enum Month {jan = 1,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec}; 
Month* month; 
enum date_state 
{ 
    good,err_flag, bad_day, bad_month, bad_year, 
}; 
//I would like to define converting operator from enum to char 
Date::date_state::operator char() 
{ 
    return err_flag; 
} 
date_state err_state; 
void clear(date_state state = good); 
date_state rdstate() const; 
void check_day(const int d)const; 
void check_month()const; 
void check_year()const; 
public: 
Date(const int d,const Date::Month& m, const int y); 

}; 

,基本上這是行不通的。

+2

我試着回答你的問題,但我的嘗試基本上沒有工作。 – Artelius 2009-12-04 09:35:34

+0

你可能想爲這個問題添加'C++'標籤... – 2009-12-04 09:36:03

+0

你寫了一個類或結構體?你是什​​麼意思,它不起作用 - 發生了什麼? – Amarghosh 2009-12-04 09:36:11

回答

0

不能爲enum date_state聲明成員函數,因爲它是一個枚舉,但你可以爲class Date這樣做的:

class Date { 
... 
    enum date_state 
    { 
     good, bad_day, bad_month, bad_year, 
    } err_flag; 

    operator char() { 
     return err_flag; 
    } 
} 

但會而是建議使用普通成員函數,因爲轉換操作符可能會被輕易使用。

1

枚舉不是類/結構體,因此您無法爲其定義轉換運算符。

我會建議編寫一個全局範圍(在命名空間內)函數來進行正確的轉換。

線沿線的東西:

char convert (Month m) { 
    switch (m) { 
    case (jan): return 'j'; 
    case (feb): return 'f'; 
    default: return 'x'; 
    } 
} 
+0

謝謝--------------------------------- – 2009-12-04 09:39:19

+0

但我一直認爲枚舉在C++中是完全成熟的類型。顯然不是。 P.S. 任何在本網站插入代碼塊的機會都會在[code = cpp]這裏的某些代碼[/ code]上完成。這與空間的buisness驅使我瘋狂。 – 2009-12-04 09:50:02

+0

C++ 0x將添加「完全成熟的恩斯穆斯」。那麼至少部分;-) – hirschhornsalz 2009-12-04 10:50:43