参数问题?至少我认为是

时间:2016-02-06 06:59:12

标签: c++ class

#include <iostream>
#include <stdio.h>
#include <iomanip>

using namespace std;

class Date
{
    private:
        int year;
        int monthNum;
        int dayNum;

    public:

    Date(int newYear = 1900, int newMonth = 1, int newDay = 1);

    void SetDate(int ChangeYear, int ChangeMonth, int ChangeDay);
    void DisplayNumerically();
    void DisplayTextually();
};

int main()
{

当调用 setDate 和参数时,我该怎么做呢? 不正确它会返回尝试更改的日期

Date f(1980, 6, 8);
f.DisplayNumerically(); /// prints "06/08/1980"
f.DisplayTextually(); /// prints "June 8, 1980"

f.SetDate(1980, 6, 31); /// prints "Error: SetDate() called with invalid date information"
f.DisplayNumerically(); /// prints "06/08/1980"
f.DisplayTextually(); /// prints "June 8, 1980"*

上面的这一部分。

return 0;
}

Date::Date(int newYear, int newMonth, int newDay)
{
    year = newYear;
    monthNum = newMonth;
    dayNum = newDay;
    if(newDay > 30)
    {
         cout <<"Error: Date created with invalid date information."<<endl;
         year = 1900;
         monthNum = 1;
         dayNum = 1;
    }
}
void Date::SetDate(int ChangeYear, int ChangeMonth, int ChangeDay)
{
    year = ChangeYear;
    monthNum = ChangeMonth;
    dayNum = ChangeDay;
    if(ChangeMonth > 12||ChangeDay > 30)
    {
         cout <<"Error: SetDate() called with invalid date information."<<endl;
         year=1;
         monthNum=1;
         dayNum=1;
    }
}
void Date::DisplayNumerically()
{
    printf("%02d",monthNum);
    printf("/%02d",dayNum);
    printf("/%04d\n",year);
}

void Date::DisplayTextually()
{
    string m;
    if( monthNum == 1)
        m = "January";
          else if( monthNum == 2)
                m = "February";
            else if( monthNum == 3)
                m = "March";
            else if( monthNum == 4)
                m = "April";
            else if( monthNum == 5)
                m = "May";
            else if( monthNum == 6)
                m = "June";
            else if( monthNum == 7)
                m = "July";
            else if( monthNum == 8)
                m = "August";
            else if( monthNum == 9)
                m = "September";
            else if( monthNum == 10)
                m = "October";
            else if( monthNum == 11)
                m = "November";
            else if( monthNum == 12)
                m = "December";
                else
                    cout <<"Invalid month input: "<< monthNum << endl;

    cout << m <<" "<<fixed<<setprecision(2)<<dayNum<<","<<year<<endl;
}

1 个答案:

答案 0 :(得分:0)

输入错误时,不要修改日期:

void Date::SetDate(int ChangeYear, int ChangeMonth, int ChangeDay)
{
    if(ChangeMonth > 12||ChangeDay > 30)
    {
         cout <<"Error: SetDate() called with invalid date information."<<endl;
    }
    else
    {
        year = ChangeYear;
        monthNum = ChangeMonth;
        dayNum = ChangeDay;
    }
}

(我假设您的有效性检查仅用于说明目的。)