世界卫生组织健康要素:c++的问题,请帮忙讲讲

来源:百度文库 编辑:查人人中国名人网 时间:2024/05/07 12:01:49
#include <iostream.h>
#include <string.h>
class Student
{
public:
Student(char* pName ):id(10)
{

strcpy(name, pName);
cout << "Constructing new student " << pName << endl;
}
/* Student(Student& s)
{
cout << "Constructing copy of" << s.name << endl;
strcpy(name, "copy of");
strcat(name, s.name);
id = s.id;
}*/
display()
{
cout << "id =" << id << endl;
}

~Student()
{
cout << "Destructing" << name << endl;
}
protected:
char name[40];
int id;
};
void fn(Student s)
{
cout << "In function fn()\n" ;
cout << "In function fn() id=" <<s.display() << endl;
}
void main()
{
Student randy("Randy");
randy.display();
fn(randy);
randy.display();
}
的运行结果是
Constructing new student Randy
id =10
In function fn()
id =10
In function fn() id=4364760
DestructingRandy
id =10
DestructingRandy
Press any key to continue
为什么在函数fn()中id=4364760 ?
还有Student::display()不能是void ?
谢谢

问题有二:第一,如楼上所说。
第二,
/* Student(Student& s)
{
cout << "Constructing copy of" << s.name << endl;
strcpy(name, "copy of");
strcat(name, s.name);
id = s.id;
}*/
应改为:

Student(Student& s)
{
cout << "Constructing copy of" << s.name << endl;
strcpy(name, "copy of");
strcat(name, s.name);
id = s.id;
} 此为拷贝构造函数,因为函数fn(Student s)参数传递的是一个Student类的变量,所以Studetn需要一个拷贝构造函数,就是上面的那个。
如果没有这个函数就会出现:
创建了一次对象,Constructing new student Randy
却要释放两次
DestructingRandy
id =10
DestructingRandy 。
还有如果构造函数用到new 申请内存空间,析构函数用到delete释放内存的话,申请了一次的空间却要释放两次,后果是无法预测的。

你把s.display()写在cout<<里面了,这时,除了s.display函数本身的输出外,还会输出s.display这个函数在内存中的地址啊,当然是一个比较怪的大整数了。

就因为你把s.display写在了cout<<里,而cout<<要求输出的不能是void类型的变量,所以你的程序中,不能给display加void类型。