一个简单的问题,求解释!!!
#include<fstream>#include<string>#include<iostream.h>using namespace std;int n; //定义一个全局变量class Teacher{private: string name; string teacherNum; int work;public: Teacher(){name="";teacherNum="";work=0;} void input();};/***定义一单链表,用于存放Teacher对象*/struct teacher{ Teacher t; struct teacher *next;};//struct teacher* void Teacher::input(){ string str; char ach[100]; char* pchTok; string w; struct teacher *teacher1,*teacher2; //定义一指向结构体的指针变量 struct teacher *head; n=0; ifstream infile("teacher.txt",ios::in|ios::nocreate); //定义输入文件流 if(!infile){ cerr<<"open error!"<<endl; exit(1); } while(infile.good()){ getline(infile,str); //读取一行数据,放到字符串中 strcpy(ach,str.c_str()); //一个汉字字符占两个字符位 ach[str.size()] = '\0'; //字符数组以'\0'作为结束标志 //每行中的元素以空格为标识断开 pchTok = strtok(ach, " "); Teacher tea; int i = 1; //用于标志读取到第几个空格 while((pchTok != NULL)){ if(i==3){ //第三个是工作量 tea.work=atoi(pchTok); cout<<tea.work<<"-----------"<<pchTok<<endl; } if(i==2){ //第二个是教师号 tea.teacherNum=pchTok; ++i; //运算之后就等于3 cout<<pchTok<<endl; } if(i==1){ //第一个是名字 tea.name=pchTok; ++i; //运算之后i就等于2 cout<<pchTok<<endl; //没写输出的时候为什么还是有两个姓名的输出 } pchTok = strtok(NULL, " "); } teacher1=teacher2=(struct teacher*)malloc(sizeof(struct teacher)); [b][size=10px]teacher1->t=tea; // 给对象赋值,出现错误[/size][/b] while(teacher1->t.name!=""){ n=n+1; if(n==1) head=teacher1; else teacher2->next=teacher1; teacher2=teacher1; teacher1=(struct teacher*)malloc(sizeof(struct teacher)); } } //return head;}int main(){ Teacher t; t.input(); return 0;}
class Teacher{private: string name; string teacherNum; int work;public: Teacher(){name="";teacherNum="";work=0;} void input();};struct teacher{ Teacher t; struct teacher *next;};int main(int argc, _TCHAR* argv[]){ teacher* pStTeater = (teacher*)malloc(sizeof(teacher)); Teacher CLSTeacher; pStTeater->t = CLSTeacher; return 0;}
[解决办法]
纠正一下:
Teacher &Teacher(const Teacher &t){ if (&t == this) return *this; name = t.name; teacherNum = t.teacherNum; work = t.work; return *this;}
[解决办法]
malloc时不会调用对象定构造函数,这是错误引起的原因。改成new就可以了
#include <iostream>#include <cstdlib>using namespace std;class Teacher{private: string name; string teacherNum; int work;public: Teacher(){name="";teacherNum="";work=0;} Teacher(const Teacher &t) { name = t.name; teacherNum = t.teacherNum; work = t.work; }// Teacher operator= (const Teacher& t) {// name=t.name;// teacherNum=t.teacherNum;// work=t.work;// return *this;// } void input();};/***定义一单链表,用于存放Teacher对象*/struct teacher{ Teacher t; struct teacher *next;};int main(void){ struct teacher* teacher1; Teacher tea;// teacher1=(struct teacher*)malloc(sizeof(struct teacher)); teacher1=new struct teacher; teacher1->t=tea;}