一个简单c++类程序问题
char *str1; str1=new char(30);与 char str1[30];有何区别,为何输入还不到20个字母,程序就崩溃了?#include<iostream>
using namespace std;
class person{
private:
char *name;
int number;
public:
person(char *str,int _number){
number=_number;
name=new char[strlen(str)+1];
strcpy(name,str);
}
void show(){ cout<<"姓名:"<<name<<endl;
cout<<"编号:"<<number<<endl;
}
};
class student:public person{
private:
int classnumber;
double score;
public:
student(char*str,int _number,int _classnumber,double _score)
:person(str,_number){
classnumber=_classnumber;
score=_score;
}
void show1(){person::show();
cout<<"学号:"<<classnumber<<endl;
cout<<"分数:"<<score<<endl;
}
};
class teacher:public person{
private:
char *department;
char *profession;
public:
teacher(char *str,int _number,char *str1,char *str2):
person(str,_number){
department=new char[strlen(str1)+1];
profession=new char[strlen(str2)+1];
strcpy(department,str1);
strcpy(profession,str2);
}
void show2(){person::show();
cout<<"部门:"<<department<<endl;
cout<<"职称:"<<profession<<endl;
}
};
void main(){
char *name;
name=new char();
cout<<"请输入学生的姓名:";
cin>>name;
int number;
cout<<"请输入学生的编号:";
cin>>number;
int classnumber;
cout<<"请输入学生的班号:";
cin>>classnumber;
double score;
cout<<"请输入学生的分数:";
cin>>score;
cout<<"\n";
cout<<"学生数据如下:"<<endl;
student s(name,number,classnumber,score);
s.show1();
cout<<"\n";
char *str;
str=new char(10);
cout<<"请输入教师的姓名:";
cin>>str;
int number1;
cout<<"请输入教师的编号:";
cin>>number1;
// char *str1;
char str1[30];
//str1=new char(30);
cout<<"请输入教师的部门:";
cin>>str1;
char *str2;
str2=new char(10);
cout<<"请输入教师的职称:";
cin>>str2;
cout<<"\n";
cout<<"教师的数据如下:"<<endl;
teacher t(str,number1,str1,str2);
t.show2();
}