标题:一个简单c++类程序问题
取消只看楼主
逆光
Rank: 2
等 级:论坛游民
帖 子:14
专家分:12
注 册:2009-9-7
结帖率:0
已结贴  问题点数:10 回复次数:0 
一个简单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();
}



                        

搜索更多相关主题的帖子: private include person public number 
2009-11-18 19:55



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-292760-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.073777 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved