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;
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;
}
- 2 回答
- 0 关注
- 201 浏览
添加回答
举报