2011-09-28 78 views
1

我只是在学习类,所以我尝试了一些基本的东西。我有一个名为Month的课程,如下所示。对于我的第一个测试,我想提供一个从1到12的数字并输出月份的名字,即。 1 = 1月C++类:传递参数

class Month 
{ 
public: 
    Month (char firstLetter, char secondLetter, char thirdLetter); // constructor 
    Month (int monthNum); 
    Month(); 
    void outputMonthNumber(); 
    void outputMonthLetters(); 
    //~Month(); // destructor 
private: 
    int month; 
}; 
Month::Month() 
{ 
    //month = 1; //initialize to jan 
} 
void Month::outputMonthNumber() 
{ 
    if (month >= 1 && month <= 12) 
    cout << "Month: " << month << endl; 
    else 
    cout << "Not a real month!" << endl; 
} 

void Month::outputMonthLetters() 
{ 
    switch (month) 
    { 
    case 1: 
     cout << "Jan" << endl; 
     break; 
    case 2: 
     cout << "Feb" << endl; 
     break; 
    case 3: 
     cout << "Mar" << endl; 
     break; 
    case 4: 
     cout << "Apr" << endl; 
     break; 
    case 5: 
     cout << "May" << endl; 
     break; 
    case 6: 
     cout << "Jun" << endl; 
     break; 
    case 7: 
     cout << "Jul" << endl; 
     break; 
    case 8: 
     cout << "Aug" << endl; 
     break; 
    case 9: 
     cout << "Sep" << endl; 
     break; 
    case 10: 
     cout << "Oct" << endl; 
     break; 
    case 11: 
     cout << "Nov" << endl; 
     break; 
    case 12: 
     cout << "Dec" << endl; 
     break; 
    default: 
     cout << "The number is not a month!" << endl; 
    } 
} 

这里是我有一个问题。我想将“num”传递给outputMonthLetters函数。我该怎么做呢?该函数是无效的,但是必须有一些方法来将变量放入类中。我是否必须公开“月”变量?

int main(void) 
{ 
    Month myMonth; 
    int num; 
    cout << "give me a number between 1 and 12 and I'll tell you the month name: "; 
    cin >> num; 
    myMonth.outputMonthLetters(); 
} 
+0

为该函数添加一个重载有什么问题:void outputMonthLetters(unsigned int monthNumber); – celavek

+1

[提高可读性](http://ideone.com/ve0PK) –

+0

@Benjamin谢谢 – dukevin

回答

4

你可能想要做的是这样的:

int num; 
cout << "give me a number between 1 and 12 and I'll tell you the month name: "; 
cin >> num; 
Month myMonth(num); 
myMonth.outputMonthLetters(); 

注意myMonth没有声明,直到它的需要,并构造采取月份数字是叫你确定哪些一个月后你正在寻找的号码。

+0

我假设你实际上实现了'Month :: Month(int)'构造函数;如果你没有,代码是'Month :: Month(int m):month(m){}' –

+0

好极了!谢谢,我明白你现在是怎么做到的! – dukevin

1

尝试使用参数的方法

void Month::outputMonthLetters(int num); 

比你可以这样做:

Month myMonth; 
int num; 
cout << "give me a number between 1 and 12 and I'll tell you the month name: "; 
cin >> num; 
myMonth.outputMonthLetters(num); 

我不是C++大师,但你不必须创建月的一个实例?

0

更改

void Month::outputMonthLetters() 

static void Month::outputMonthLetters(int num) 
{ 
    switch(num) { 
    ... 
    } 
} 

即一个参数添加到方法,和(可选),使其静态的。但是这不是一个很好的例子,开始...

+0

你为什么要改变它?它被称为重载 - 可以有多个具有相同名称但具有不同参数类型或参数数量的方法。 – celavek