一、程式改錯題
使用VC++6.0開啟考生資料夾下的源程式檔案,該程式執行時有錯,請改正程式中的錯誤,使程式輸出的結果為
150
200
注意:錯誤的語句在//******error******的下面,修改該語句即可。
提示:定義Numl為一個整型資料位長的變數。
試題程式:
#include
//******error******
struct
{
//******error******
intNuml:1;
intNum2;
}
MyStruct;
voidmain()
{
MyStructmstr;
1=150;
2=15;
//******error******
int*ptr=&;
cout<<*ptr< *ptr=200;
cout<<*ptr< } (1)“typedefstruct”。
(2)“intNuml:32;”或“intNuml;”。
(3)“int*ptr=(int*)&mstr;”。
【解析】第1處是定義結構體,結構體定義的'一般形式為
struct(結構體名>
{
<成員列表>
}
(變數名列表);
程式當中定義結構體名放在後面,MyStruct為結構體變數型別,相當於typedef為已有的型別定義一個新的型別,第1處應改為“typedefstruct”。第2處是定義Numl為一個整型資料變數,整型資料位數為32(4位元組),因此第2處應改成“intNuml:32;”或“intNuml;”。ptr為整型資料指標,mstr為MyStruct型別結構變數,兩者型別不一致應該做強制型別轉換,第3處應改成“int*ptr=(int*)&mstr;”,表示將mstr的地址給ptr,ptr指向MyStruct的第一個域Numl,Numl也是整型,型別一致,故可通過ptr指標來改變Numl的值。
二、綜合應用題
使用VC++6.0開啟考生資料夾下的源程式檔案,其中定義了用於表示日期的類Date,但類Date的定義並不完整,按要求完成下列操作,將類的定義補充完整。
(1)定義私有成員變數year、month、day,分別表示年、月、日,型別為int。請在註釋1後新增適當的語句。
(2)完成建構函式,分別給year、month、day賦值,請在註釋2後新增適當的語句。
(3)完成過載符號“+=”的定義,請在註釋3後新增適當的語句。
(4)完成函式print列印函式,如2005年1月5日到螢幕和檔案格式相同,請在註釋4後新增適當的語句。
注意:增加程式碼,或者修改程式碼的位置已經用符號表示出來。請不要修改其他的程式程式碼。
試題程式:
#include
#include
#include
#include
usingnamespacestd;
voidWriteFile(intc)
{
ofstreamout1;
("",ios_base::app);out1< e();
}
voidWriteFile(char*str)
{
ofstreamout1;
("",ios_base::app);out1< e();
}
voidClearFile()
{
ofstreamout1;
(""):
e();
}
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();
DateNationa1_day(2004,10,5);
National_day+=3;
National_t();
return0;
} (1)應新增“year=y;month=m;day=d;”。
(2)應新增“Date&operator+=(intm)”。
(3)應新增“intyear,month,day;”。
(4)應新增“cout<
【解析】本題要求私有成員變數year、month、day為整形表示方法,所以註釋3應新增“intyear,month,day;”;註釋1要求分別給year、month、day賦值,根據上下文提意,所以應新增“year=y;month=m;day=d;”;註釋2是對“+=”運算子的重栽,Date&operator4+=(intm);第4處列印輸出年、月、日,C++語言中,輸出使用cout。