#include <iostream> #include <string> using namespace std; class Menber{ public: char *gname; char *gsex; int gage; Menber(char *n,char *s,int a); void SetName(){ gname=sname; } void SetSex(){ gsex=ssex; } void SetAge(){ gage=sage; } void Showme(){ cout<<"--name--"<<gname<<endl; cout<<"a"<<endl; cout<<"--sex--"<<gsex<<endl; cout<<"b"<<endl; cout<<"--age--"<<gage<<endl; cout<<"c"<<endl; } ~Menber(){}; private: char *sname; char *ssex; int sage; }; Menber::Menber(char *n,char *s,int a) { sname=n; ssex=s; sage=a; } class Teacher:public Menber{ public: Teacher(char *n,char *s,int a,char *o,int m):Menber(gname,gsex,gage){ / /这里是为了集成基类的数据 money=m; objection=o; } Showme(){ Menber::Showme(); cout<<"--objectiong--"<<objection<<endl; cout<<"--money--"<<money<<endl; } ~Teacher(){}; private: int money; char *objection; }; class Student:public Menber{ public: Student(char *n,char *s,int a,int id):Menber(gname,gsex,gage){ ID=id; } Showme(){ cout<<"1"<<endl; Menber::Showme(); cout<<"2"<<endl; cout<<"--ID--"<<ID<<endl; } ~Student(){}; private: int ID; }; void main(){ Menber m1("kjhk","m",20); m1.Showme(); cout<<endl; Student s1("laoli","w",10,10145); s1.Showme(); cout<<"111"<<endl; }
可以帮本人看下Menber类那里出现的问题吗?代码运行后显示 已停止工作。
10
char *sname;
char *ssex;
int sage;
但没有初始化以下成员:
char *gname;
char *gsex;
int gage;
m1.Showme(); 这句函数中将使用了未初始化的变量
5
顶,你的setname(),setage(),setsex()没用上gname/sex/age没初始化
10
派生类的构造函数的参数不对应。你char*n,member(j就应该是n,而不是gname)
15
#include <string>
using namespace std;
class Menber{
public:
char *gname;
char *gsex;
int gage;
Menber(char *n,char *s,int a);
void SetName(){
gname=sname;
}
void SetSex(){
gsex=ssex;
}
void SetAge(){
gage=sage;
}
void Showme(){
SetName() ; //调用一下这三个参数
SetSex() ;
SetAge() ;
cout<<“–name–“<<gname<<endl;
cout<<“a”<<endl;
cout<<“–sex–“<<gsex<<endl;
cout<<“b”<<endl;
cout<<“–age–“<<gage<<endl;
cout<<“c”<<endl;
}
~Menber(){};
private:
char *sname;
char *ssex;
int sage;
};
Menber::Menber(char *n,char *s,int a)
{
sname=n;
ssex=s;
sage=a;
}
class Teacher:public Menber{
public:
Teacher(char *n,char *s,int a,char *o,int m):Menber(n,s,a){ //构建函数初始化父类构建函数参数错误
money=m;
objection=o;
}
void Showme(){
Menber::Showme();
cout<<“–objectiong–“<<objection<<endl;
cout<<“–money–“<<money<<endl;
}
~Teacher(){};
private:
int money;
char *objection;
};
class Student:public Menber{
public:
Student(char *n,char *s,int a,int id):Menber(n,s,a) // //构建函数初始化父类构建函数参数错误
{
ID=id;
}
void Showme(){
cout<<“1″<<endl;
Menber::Showme();
cout<<“2″<<endl;
cout<<“–ID–“<<ID<<endl;
}
~Student(){};
private:
int ID;
};
int main(int argc,char *argv[]){
Menber m1(“kjhk”,”m”,20);
m1.Showme();
cout<<endl;
Student s1(“laoli”,”w”,10,10145);
s1.Showme();
cout<<“111″<<endl;
return 0 ;
}
用指针去存储数据, 以后空间很难管理, 原因是不知道是指向常量字符串, 还是 堆内存分配的字符串.
释放堆内存管理也比较麻烦。
class Menber{
public:
Menber(char *n,char s,int a) {
strncpy(m_szname,n,sizeof(m_szname)-1) ;
m_chSex = s ;
m_iage = a ;
}
private:
char m_szname[32] ;
char m_chSex ;
int m_iage ;
}
10
s1变量中的那几个变量仍然没有初始化