枚举

2009-12-04 166 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