#include <iostream>
#include <string>
class Date
{
public:
Date(int, int, int);
Date(std::string, int, int);
void print();
void printFullDate();
int getMonth();
int getDay();
int getYear();
void setMonth(int);
void setDay(int);
void setYear(int);
private:
int mm,dd,yy;
std::string mstr;
};
这是我的类Date
的头文件以下是实施
#include <iostream>
#include "Date.h"
using namespace std;
Date::Date(int mm, int dd, int yy)
{
if(mm < 1 || mm > 12 )
{
cout << "Please Enter a Valid Month (1-12)";
cin >> mm;
}
if(mm == 1 || mm == 3 || mm == 5 || mm == 7 || mm == 8 || mm == 10 || mm == 12)
{
if(dd < 1 || dd > 31)
{
cout << "Please Enter a Valid Date For the Month Entered(1-31)";
cin >> dd;
}
}
if(mm == 4 || mm == 6 || mm == 9 || mm == 11)
{
if(dd < 1 || dd >30)
{
cout << "Please Enter a Valid Date for the Month Entered(1-30)";
cin >> dd;
}
}
if ( (yy % 4 == 0 && yy % 100 != 0) || ( yy % 400 == 0))
{
if(mm == 2)
{
if( dd < 1 || dd > 29)
{
cout << "Please Enter a Valid Date for the Month Entered(1-29)";
cin >> dd;
}
}
}
else
{
if(mm == 2)
{
if(dd < 1 || dd > 28)
{
cout << "Please Enter a Valid Date for the Month Entered(1-28)";
cin >> dd;
}
}
}
if (yy < 1)
{
cout << "Please Enter a Valid Date of the era AD";
cin >> yy;
}
switch(mm)
{
case 1:
mstr = "January";
break;
case 2:
mstr = "February";
break;
case 3:
mstr = "March";
break;
case 4:
mstr = "April";
break;
case 5:
mstr = "May";
break;
case 6:
mstr = "June";
break;
case 7:
mstr = "July";
break;
case 8:
mstr = "August";
break;
case 9:
mstr = "September";
break;
case 10:
mstr = "October";
break;
case 11:
mstr = "November";
break;
case 12:
mstr = "December";
break;
}
}
Date::Date(string mstr, int dd, int yy)
{
}
void Date::print()
{
cout << "MM/DD/YYYY: " << mm << "/" << dd << "/" << yy << endl;
}
void Date::printFullDate()
{
cout << "Month DD, YYYY: " << mstr << " " << dd << ", " << yy << endl;
cout << "**********" << endl << endl;
}
void Date::setDay(int day)
{
dd = day;
}
void Date::setMonth(int month)
{
mm = month;
}
void Date::setYear(int year)
{
yy = year;
}
int Date::getDay()
{
return dd;
}
int Date::getMonth()
{
return mm;
}
int Date::getYear()
{
return yy;
}
当我调用函数Date(int,int,int)时,它会很好地运行。但是,当我调用print函数时,变量不会保留构造函数中指定的值。当构造函数更正一个月,一天或一年时,该数据不会在打印时输出。而是输出原始未更改的值。我相信一旦传递给构造函数的变量应该对整个类保持不变。我搞不清楚了。任何帮助将不胜感激。
答案 0 :(得分:1)
那是因为你的构造函数的参数......
Date::Date(int mm, int dd, int yy)
...是具有相同名称的类成员变量的不同变量。我通常将成员命名为尾随下划线,例如mm_, dd_, yy_
- 然后在构造函数的末尾,您可以像...一样分配给它们
mm_ = mm; dd_ = dd; yy_ = yy; mstr_ = mstr;