我写了个Worker类,有姓名、年龄、薪金等数据成员。先用list管理该类的对象,建立两个链表,每个链表存入3个Worker类的对象。在使用链表的merge算法将这两个链表合并在一起时出错。
代码如下:
#include <iostream>
#include <list>
using namespace std;
class Worker
{
char name[10]; int age; double salary;
public:
Worker(char *Name="noName",int Age=20,double Salary=2000)
{
strncpy(name,Name,9);
age=Age;
salary=Salary;
}
Worker(const Worker& w)
{
strcpy(name,w.name);
age=w.age;
salary=w.salary;
}
void SetData(char *Name="noName",int Age=20,double Salary=2000)
{
strncpy(name,Name,9);
age=Age;
salary=Salary;
}
void Display()
{
cout<<"员工:"<<name<<" ";
cout<<"年龄:"<<age<<" ";
cout<<"工资:"<<salary<<endl<<endl;
}
};
void main()
{
//创建Worker对象
Worker W1[3],W2[3];
W1[1].SetData("员工11",30,3000); W1[0].SetData("员工10",30,3000); W1[2].SetData("员工12",30,3000);
W2[1].SetData("员工21",30,3000); W2[0].SetData("员工20",30,3000); W2[2].SetData("员工22",30,3000);
list<Worker> L1,L2;
list<Worker>::iterator tor;
//在链表中存入Worker对象
for(int i=0; i<3; i++)
{
L1.push_back(W1[i]);
L2.push_back(W2[i]);
}
//迭代器输出链表L1、L2各节点对象的数据成员
cout<<"L1:"<<endl;
for(tor=L1.begin(); tor!=L1.end(); tor++)
tor->Display();
cout<<"L2:"<<endl;
for(tor=L2.begin(); tor!=L2.end(); tor++)
tor->Display();
//使用merge()成员函数合并L2到L1
L1.merge(L2); //此处出错!!!!!
cout<<"合并后的L1:"<<endl;
for(tor=L1.begin(); tor!=L1.end(); tor++)
tor->Display();
}
幕布斯6054654
素胚勾勒不出你
相关分类