Student類結構說明:
Student類的資料成員包括:
①私有資料成員:學號no(char[]型),姓名name(char[]型),年齡age(int型)。
②靜態資料成員:sum(int型),作用為統計當前時刻Student類物件的總數。
Student類成員函式包括:
①定義有參建構式Student(char *,char *,int)和拷貝建構式Student(Student &),其中有參建構式引數默認值為空串或0(當字串引數為NULL時視為空串處理),輸出資訊“Constructor run”,拷貝建構式輸出資訊“CopyConstructor run”
②定義解構式,解構式輸出資訊“Destructor run”
③公有函式成員:void setNo(char *)和char* getNo()分別回傳和設定no(當引數為NULL時視為空串處理)
④公有函式成員:void setName(char* )和char* getName()分別回傳和設定name(當引數為NULL時視為空串處理)
⑤公有函式成員:void setAge(int)和int getAge()分別回傳和設定age
⑥公有函式成員:void show()用于顯示當前物件資訊age。假定“學號=20190327,姓名=doublebest,年齡=21”的學生物件的資訊顯示格式如下:
No:20190327,Name:doublebest,Age:21
裁判測驗程式樣例:
#include<iostream>
using namespace std;
請在這里填寫答案
int main(){
char s1[10]="20190327";
char s2[20]="doublebest";
Student stu1(s1,s2);
stu1.setAge(21);
stu1.show();
Student stu2=stu1;
cin.getline(s1,10,'\n');
cin.getline(s2,20,'\n');
stu2.setNo(s1);
stu2.setName(s2);
stu2.show();
return 0;
}
輸入樣例:
20190327
doublebest
輸出樣例:
Constructor run
NumTotal:1
No:20190327,Name:doublebest,Age:21
CopyConstructor run
NumTotal:2
No:20190327,Name:doublebest,Age:21
Destructor run
NumTotal:1
Destructor run
NumTotal:0
uj5u.com熱心網友回復:
#include<iostream>
using namespace std;
//請在這里填寫答案
#include<cstring>
#define MAX 255
class Student {
private:
char no[MAX+1];
char name[MAX+1];
int age;
public:
static int sum;
Student(const char*,const char*,int);
Student(const Student&);
void setNo(const char*);
char* getNo();
void setName(const char*);
char* getName();
void setAge(int);
int getAge() const;
void show() const;
~Student();
};
int Student::sum=0;
Student::Student(const char* no_=NULL,const char* name_=NULL,int age_=0) {
setNo(no_);
setName(name_);
age=age_;
sum++;
cout<<"Constructor run"<<endl;
cout<<"NumTotal:"<<sum<<endl;
}
Student::Student(const Student& other) {
setNo(other.no);
setName(other.name);
age=other.age;
cout<<"CopyConstructor run"<<endl;
sum++;
cout<<"NumTotal:"<<sum<<endl;
}
void Student::setNo(const char* no_) {
if(no_!=NULL){
strncpy(no,no_,MAX);
no[MAX]='\0';//src長度大于MAX時,strncpy不會寫入'\0'
}
else
no[0]='\0';
}
char* Student::getNo() {
return no;
}
void Student::setName(const char* name_) {
if(name_!=NULL){
strncpy(name,name_,MAX);
name[MAX]='\0';
}
else
name[0]='\0';
}
char* Student::getName() {
return name;
}
void Student::setAge(int age_) {
age=age_;
}
int Student::getAge() const {
return age;
}
void Student::show() const {
cout<<"No:"<<no<<","
<<"Name:"<<name<<","
<<"Age:"<<age<<endl;
}
Student::~Student() {
cout<<"Destructor run"<<endl;
sum--;
cout<<"NumTotal:"<<sum<<endl;
}
int main() {
char s1[10]="20190327";
char s2[20]="doublebest";
Student stu1(s1,s2);
stu1.setAge(21);
stu1.show();
Student stu2=stu1;
cin.getline(s1,10,'\n');
cin.getline(s2,20,'\n');
stu2.setNo(s1);
stu2.setName(s2);
stu2.show();
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/271000.html
標籤:C++ 語言
上一篇:編程入門:零基礎想要學好C/C++編程?那你一定要看看這五個步驟!
下一篇:如何實作外部程式對系統服務的控制
