#include<iostream>#include<string>using namespace std;class Student{private:int age;char *name;public:Student(int m,char *n);Student();~Student();void SetMember(int m,char *n);int GetAge();char *GetName();};Student::Student(int m,char *n){age=m;if(n){name=new char[strlen(n)+1];strcpy(name,n);}}Student::Student(){age=0;name="unnamed";}Student::~Student(){cout<<"Destructor called."<<endl;delete []name;}int Student::GetAge(){return age;}char *Student::GetName(){return name;}void Student::SetMember(int m,char *n){age=m;if(n){name=new char[strlen(n)+1];strcpy(name,n);}else name=0;}int main(){Student stu[3]={Student(13,"wang")};stu[2].SetMember(12,"zhang");cout<<stu[0].GetAge()<<","<<stu[0].GetName()<<endl;cout<<stu[1].GetAge()<<","<<stu[1].GetName()<<endl;cout<<stu[2].GetAge()<<","<<stu[2].GetName()<<endl;return 0;}題目要求是:定義一個(gè)學(xué)生類 Student ,設(shè)計(jì)私有數(shù)據(jù)成員:年齡 int age; 姓名 char *name; 公有成員函數(shù): 構(gòu)造函數(shù) 帶參數(shù)的構(gòu)造函數(shù) Student ( int m,char *n ) ; 不帶參數(shù)的構(gòu)造函數(shù) Student ( ) ; 析構(gòu)函數(shù) ~ Student ( ) ; 釋放由 name 申請(qǐng)的動(dòng)態(tài)空間 改變數(shù)據(jù)成員值函數(shù) void SetMember ( int m,char *n ) ;獲取數(shù)據(jù)成員函數(shù) int Getage ( ) ; char *Getname ( ) ; 在 main ( ) 中定義一個(gè)有 3 個(gè)元素的對(duì)象數(shù)組并分別初始化,然后輸出對(duì)象數(shù)組的信息, main 函數(shù)的部分內(nèi)容如下: int main ( ) { Student stu[3]={Student(13,“wang”);……} // 第一個(gè)元素調(diào)用帶能構(gòu)造函數(shù)初始化 // 第二、三個(gè)元素由無(wú)參構(gòu)造函數(shù)初始化,默認(rèn)年齡為 0 ,姓名為unnamed; //stu[2]. SetMember ( 12,"zhang“ ) ; // 修改第三個(gè)元素的數(shù)據(jù)成員值
我的程序在運(yùn)行時(shí)出錯(cuò),應(yīng)該是內(nèi)存使用上的問(wèn)題,請(qǐng)問(wèn)應(yīng)該怎么修改?謝謝了??!
慕神8447489
2023-03-15 21:17:46