猿问

请问需要构造一个学生类CStudent,该怎么做?

要求如下:
1,构造一个学生类CStudent,要求如下:
具有两个保护的成员:姓名和学号
实现带参数的构造函数,在构造函数中输出“带参构造函数被调用”
实现拷贝构造函数,在其中输出“拷贝构造函数被调用”
实现析构函数,在析构中输出“析构函数被调用”
在类的外部,声明一个全局函数 void PrintInfo(CStudent stu);实现对学生信息的输出
在main中声明CStudent的对象,并利用PrintInfo实现对它的调用。

海绵宝宝撒
浏览 202回答 2
2回答

肥皂起泡泡

三个文件//头文件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;

holdtom

#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;}
随时随地看视频慕课网APP
我要回答