亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

請問需要構造一個學生類CStudent,該怎么做?

請問需要構造一個學生類CStudent,該怎么做?

PHP
海綿寶寶撒 2022-01-06 11:07:49
要求如下:1,構造一個學生類CStudent,要求如下:具有兩個保護的成員:姓名和學號實現帶參數的構造函數,在構造函數中輸出“帶參構造函數被調用”實現拷貝構造函數,在其中輸出“拷貝構造函數被調用”實現析構函數,在析構中輸出“析構函數被調用”在類的外部,聲明一個全局函數 void PrintInfo(CStudent stu);實現對學生信息的輸出在main中聲明CStudent的對象,并利用PrintInfo實現對它的調用。
查看完整描述

2 回答

?
肥皂起泡泡

TA貢獻1829條經驗 獲得超6個贊

三個文件
//頭文件CStudent.h
#ifndef STUDENT
#define STUDENT
#include<iostream>
class CStudent
{
public:
CStudent(char* amingzi="mingzi",int axuehao=1);
CStudent(const CStudent& stu);
~CStudent();
char* getname()const;
int getxuehao()const;
private:
char* mingzi;
int xuehao;
};
inline void PrintInfo(const CStudent& stu)
{
std::cout<<"名字:"<<stu.getname()<<std::endl
<<"學號:"<<stu.getxuehao()<<std::endl;
}
#endif
//CStudent.cpp文件
#include"Cstudent.h"
#include<string>
#include<iostream>
using namespace std;
CStudent::CStudent(char* amingzi,int axuehao)
{
mingzi=new char[strlen(amingzi)+1];
strcpy(mingzi,amingzi);
xuehao=axuehao;
cout<<"帶參構造函數被調用"<<endl;
}
CStudent::CStudent(const CStudent& aCStudent)
{
mingzi=new char[strlen(aCStudent.mingzi)+1];
strcpy(mingzi,aCStudent.mingzi);
xuehao=aCStudent.xuehao;
cout<<"拷貝構造函數被調用"<<endl;
}
CStudent::~CStudent()
{
delete [] mingzi;
cout<<"析構函數被調用"<<endl;
}
char* CStudent::getname()const
{
return mingzi;
}
int CStudent::getxuehao()const
{
return xuehao;
}
//main.cpp文件
#include"CStudent.h"
int main()
{
CStudent a("奧巴馬",100);
PrintInfo(a);
CStudent b(a);
PrintInfo(b);
return 0;
}
沒有重載=運算符,所以不能b=a;


查看完整回答
反對 回復 2022-01-09
?
holdtom

TA貢獻1805條經驗 獲得超10個贊

#include <iostream>
#include <string.h>
using namespace std;
class CStudent
{
public:
CStudent(char* n, char* i)
{
strcpy(name, n);
strcpy(id, i);
cout << "帶參構造函數被調用" << endl;
}
CStudent(const CStudent& stu)
{
strcpy(name, stu.name);
strcpy(id, stu.id);
cout << "拷貝構造函數被調用" << endl;
}
~CStudent()
{
cout << "析構函數被調用" << endl;
}
void Print()
{
cout << name << " " << id << endl;
}
protected:
char name[20];
char id[20];
};

void PrintInfo(CStudent stu)
{
stu.Print();
}

int main()
{
CStudent stu1("abc", "1234");
CStudent stu2(stu1);
PrintInfo(stu1);
return 0;
}



查看完整回答
反對 回復 2022-01-09
  • 2 回答
  • 0 關注
  • 264 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號