return name
return sex
都要个函数接口不是太麻烦了吗?
吧teacher设为友员 我使了但是不行啊
他说我这有错
{num=1001;name[]="chen";sex[]="boy";CJ[0]=89.0;CJ[1]=78;CJ[2]=100;}
是不是赋值有问题啊
name[]="chen"能这样赋吗。如果不能因改如何呢,难道要一个字符一个字符的赋吗,太麻烦了吧?
有没有什么好办法啊?
我又把它改成这样
#include <iostream>
using namespace std;
class student
{private:
int num;
char *name;
char *sex;
double CJ[3];
public:
friend class teacher;
student(){num=1001;name="chen";sex="boy";CJ[0]=89.0;CJ[1]=78;CJ[2]=100;}
void display();
};
class teacher
{private:
int num;
char *name;
char *sex;
public:
teacher(){num=0;name=NULL;sex=NULL;}
teacher(student &s){num=s.num;strcpy(name,s.name);strcpy(sex,s.sex);}
void display();
};
void teacher::display()
{cout<<num<<" "<<name<<" "<<sex<<endl;}
int main()
{
teacher t;
student s;
t=teacher(s);
t.display();
return 0;
}
运行是能运行了 但是...
#include <iostream>
using namespace std;
class student
{private:
int num;
char *name;
char *sex;
double CJ[3];
public:
friend class teacher;
student(){num=1001;name="chen";sex="boy";CJ[0]=89.0;CJ[1]=78;CJ[2]=100;}
void display();
};
class teacher
{private:
int num;
char *name;
char *sex;
public:
teacher(){num=0;name=new char[20];sex=new char[20];}
void Teacher(student &s){num=s.num;strcpy(name,s.name);strcpy(sex,s.sex);}
void display();
~teacher(){delete []name;delete []sex;}
};
void teacher::display()
{cout<<num<<" "<<name<<" "<<sex<<endl;}
int main()
{
teacher t;
student s;
t.Teacher(s);
t.display();
return 0;
}
如果你非要象你那么做就这样
如果你非要象你那么做就这样
#include <iostream>
using namespace std;
class student
{private:
int num;
char *name;
char *sex;
double CJ[3];
public:
friend class teacher;
student(){num=1001;name="chen";sex="boy";CJ[0]=89.0;CJ[1]=78;CJ[2]=100;}
void display();
};
class teacher
{private:
int num;
char *name;
char *sex;
public:
teacher(student &s){name=new char[20];sex=new char[20];num=s.num;strcpy(name,s.name);strcpy(sex,s.sex);}
void display();
~teacher(){delete []name;delete []sex;}
};
void teacher::display()
{cout<<num<<" "<<name<<" "<<sex<<endl;}
int main()
{
student s;
teacher t(s);
t.display();
return 0;
}
你把teacher(student &s)做成拷贝函数一样的了,所以这个函数就在刚定义teacher时调用
并且,还需要分配空间