c++函数的声明与定义很简单的小问题,

来源:百度知道 编辑:UC知道 时间:2024/05/31 09:46:57
举个例子

A:

#include <iostream>
using namespace std;
#include <conio.h>
struct Time
{
int year;
int month;
int day;
int hour;
int min;
int sec;
};
void setTime(Time p);
void showTime(Time p);
int main()
{

Time currentTime;
setTime(currentTime);
getch();
showTime(currentTime);
getch();
}

void setTime(Time p)
{
cout<<"请设置时间: 年 月 日 小时 分钟 秒 "<<endl;
cin>>p.year>>p.month>>p.day>>p.hour>>p.min>>p.sec;
}
void showTime(Time p)
{
cout<<"时间已设为:"<<p.year<<"年"<<p.month<<"月"<<p.day<<"日"<<p.hour<<"小时"<<p.min<<"分"<<p.sec<<"秒&quo

c 和 C++ 对结构和类的对象是按值传送的,你
A
里面的
setTime(Time p)
很明显传给setTime的Time虽然在setTime中设置了值,但却不会影响外面的那个Time。应该用
setTime(Time& p)
这个直接说了是“引用”
B
里面setTime本身没有问题,但既然是指针,应该是
cin>>p->year>>p->month>>p->day>>p->hour>>p->min>>p->sec;
showTime也一样。
而且函数调用要传递地址:
setTime(¤tTime);

showTime(¤tTime);