为什么要写成(day D),不能写成(day &D)呢?求解释

#include"iostream.h"
enum day{Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday};
void nextday(day &D);
void display(day D);
int main()
{
day today=Sunday;
for(int i=0;i<7;i++)
{
cout<<"Data in today="<<today<<endl;
display(today);
nextday(today);
}
return 0;
}
void nextday(day &D)
{
switch(D)
{
case Sunday:
D=Monday;
break;
case Monday:
D=Tuesday;
break;
case Tuesday:
D=Wednesday;
break;
case Wednesday:
D=Thursday;
break;
case Thursday:
D=Friday;
break;
case Friday:
D=Saturday;
break;
case Saturday:
D=Sunday;
break;
}
}
void display(day D)// 请问这里为什么要写成(day D)为什么不能写成(day &D)
{
switch(D)
{
case Sunday:
cout<<"Sunday"<<endl;
break;
case Monday:
cout<<"Monday"<<endl;
break;
case Tuesday:
cout<<"Tuesday"<<endl;
break;
case Wednesday:
cout<<"Wednesday"<<endl;
break;
case Thursday:
cout<<"Thursday"<<endl;
break;
case Friday:
cout<<"Friday"<<endl;
break;
case Saturday:
cout<<"Saturday"<<endl;
break;
}
}

慕尼黑的夜晚无繁华
浏览 104回答 3
3回答

慕少森

也成 day&D 也是可以的,即运行结果和写成day D是一样的 但并不是一种好的做法,因为你这样你就可以在函数中改变D的值了,但这个函数是不允许改变D的值的(把今天是星期几输出,你改它值干的) 最好写成 const day & D ,这样就可以了.

有只小跳蛙

能改啊,将函数说明也改成void display(day &D)就行了

慕慕森

可以写成day&D,但是这样就能通过函数改变D的值,如1楼的最好写成const day&D,这样的引用即不能通过函数改变D的值
打开App,查看更多内容
随时随地看视频慕课网APP