问答题

使用VC++6.0打开考生文件夹下的源程序文件3.cpp,其中定义了用于表示日期的类Date,但类Date的定义并不完整,按要求完成下列操作,将类的定义补充完整。
(1)定义私有成员变量year、month、day。分别表示年、月、日,类型为int。请在注释1后添加适当的语句。
(2)完成构造函数,分别给year、month、day赋值,请在注释2后添加适当的语句。
(3)完成重载符号“十=”的定义,请在注释3后添加适当的语句。
(4)完成print打印函数,输出到屏幕和文件的格式相同,请在注释4后添加适当的语句。
注意:仅在函数指定位置添加语句,请勿改动主函数main与其他函数中的任何内容。
程序正常运行,输出的结果为2008年11月813。
试题程序:
#include(iostream.h)
#include(fstream)
#include(iomanip)
#include<cmath)
usingnamespacestd;
voidWriteFile(intc)
{
ofstreamout1;
out1.open("3.txt",ios_base::app);
out1<<C<<';
out1.close();
}
voidWriteFile(char*str)
{
ofstreamoutl;
out1.open("3.txt",ios_base::app);
out1<<str;
out1.close();
}
voidClearFile()
{
ofstreamout1;
out1.open("3.txt");
out1.close();
}
classDate
{
public:
Date(inty,intm,intd)
{
//********1********
}
voidprint();
//********2********

{
month+=m;
inti=month/12:
intj=month%12;
if(j==0)
{year+=(i-1);
month=12;
}
else
{
year+=i:
month=j;
}
return*this;
}
private:
//********3********
};
voidDate::print()
{
//********4********
WriteFile(year):
WriteFile("年");
WriteFile(month);
WriteFile("月");
WriteFile(day);
WriteFile("日");
}
intmain()
{
ClearFile();
DateOly_day(2008,8,8);
Olyday+=3:
Oly_day.print();
return0;
}

【参考答案】

(1)应添加“year=y;month=m;day=d;”。
(2)应添加“Date&operator+=(intm)”。
(3)应添加“intyear,month,day;”。
(4)应添加“cout<<year<<"年"<<month<<"月"<<day<<"日”<<endl;”。
【解析】本题中第1处要求“完成构造函数,分别给year、month、day赋值”。在程序中“Date(inty,intm,intd)”的构造函数中添加给year、month、day赋值的语句,即在第1处添加“year=y;month=m;day=d;”。第2处要求“完成重载符号‘+=’的定义”。在C++中,运算符重栽的定义方法是定义一个重载运算符的函数,格式为函数operator+重载运算符号+,所以这里补全“Date&operator+=(intm)”。第3处要求“定义私有成员变量year、month、day”。在C++程序的private区域中添加变量year、month、day的定义,即在第3处添加“intyear,month,day;”。第4处要求“完成函数print()打印函数”。在C++中的print函数中补全其打印功能,即在第四个标识下添加“eout<<year<<"年"<<month<<"月"<<day<<"日"<<endl;”。

(↓↓↓ 点击下方‘点击查看答案’看答案解析 ↓↓↓)

相关考题

判断题 甲土的饱和度大于乙土,甲土的含水量就一定比乙土高。( )

问答题 (1)应添加“#defineTRUE1”。 (2)应添加“classA1;”。 (3)应添加“friendboolfunc(A2&objl,Al&obj2);”。 (4)将“retllin”补充完整为“returnobjl.m_A2==TRUE&&obj2.m_A1==TRUE;”。 【解析】#define命令一般用一个指定的标识符(即宏 名)来代表一个字符串,其定义形式一般为“#define宏名(参数表)字符串”,因此第1处应添加“#defineTRUEl”。类声明格式为“class<类名>;”,故第2处应添加“class A1;”。友元不是本类的成员函数,在它的函数体内可以通过对象名来访问类的私有成员和保护成员。友元函数是在类声明中由关键字friend修饰的非成员函数,第3处应添加“friendboolfune(A2&objl,Al&obj2);”。函数func返回变量m_A2和m_A1的逻辑与运算结果,因此第4处的语句应改为“returnobj1.m_A2==TRUE&&obj2.m_A1==TRUE;”。

问答题 使用VC++6.0打开考生文件夹下的源程序文件1.cpp,该程序运行时有错.请改正其中的错误,使程序正常运行,并使程序输出的结果为 Maxis7 提示:max函数用于找出两个数中的最大值,并作为函 数值返回。 注意:错误的语句在//******error******的下面,修改该语句即可。 试题程序: #include<iostream> usingnamespacestd; //******error****** intmax(inta,intb) { if(a<b) { intt=a; a=b: b=t; } returnb; } intmain() { intm=-3: intn=7: //******error****** max(-3,n); cout<<"Maxis"<<m<<endl; return0; }