C++程序:这3种写法的区别?

来源:百度知道 编辑:UC知道 时间:2024/06/15 18:00:13
#include <iostream>
#include <string>
using namespace std;
struct Person
{
int no;
string name;
int age;
int salary;
Person *next;
};
Person *head;
Person *insert(Person *f)
{
Person *s,*p,*q;
s=new Person;
//s=f;
s->no = f->no;
s->name = f->name;
s->age = f->age;
s->salary = f->salary;
s->next=NULL;
if(head==NULL)
{
head=s;
return head;
}
if(head->no>s->no)
{
s->next=head,head=s;
return head;
}
for(q=head,p=head->next;p;q=p,p=p->next)
if(p->no>s->no)
{
s->next=p;
q->next=s;
return head;
}
q->next=s;//p是否也行?
return head;
}
void display( Person *head)//不用const是否可以?{
cout<<"排序后的员工信息如下:"<<endl;

1.q->next=s;//p是否也行? 不行,他们是不同的节点,换成了p,你就别想执行正确的操作了!
2.void display( Person *head)//不用const是否可以? 可以,不过那样人家可以在这个成员函数中修改你的数据了,会导致不必要的错误!所以在成员函数中不涉及修改数据的,都应该设为const函数;
3.为什么不能写成:
Person *insert(Person *f)
{
Person *s,*p,*q;
s=new Person;
s=f;
s->next=NULL;
因为你没定义=的重载,编译是不会知道你想把那些值赋过去!
比如你在类中定义个:
Person& operator=(const Person &f)
{
this->no = f->no;
this->name = f->name;
this->age = f->age;
this->salary = f->salary;
}
你就可以那样写了.

s=f和s->no = f->no;
s->name = f->name;
s->age = f->age;
s->salary = f->salary;
是不一样的,前者是将f指向的内存地址赋给s,即f和s公用一个内存单元,后者是将f复制到s,两者在内存中的位置不同,这应该就是原因