|
#include <iostream>
#include <string>
using namespace std;
class CStudent
{
public:
char * p_name;
char sex;
int num;
int age;
CStudent();
CStudent(char* pname, char t_sex, int t_num, int t_age);
~CStudent();
CStudent(CStudent& stud);
};
CStudent::CStudent(CStudent& stud)//拷贝构造函数,博主syc的答案
{
int dst_name_len = 0;
if (stud.p_name) dst_name_len = strlen(stud.p_name);
this->p_name = NULL;
if (dst_name_len > 0)
{
this->p_name = new char[dst_name_len + 1];
memset(this->p_name, 0, dst_name_len + 1);
strcpy(this->p_name, stud.p_name);
}
this->sex = stud.sex;
this->num = stud.num;
this->age = stud.age;
}
CStudent::CStudent(char* pname, char t_sex, int t_num, int t_age) :sex(t_sex), num(t_num), age(t_age)//构造函数
{
int len=strlen(pname);
p_name=new char(len+1);
memset(p_name,0,(len+1));
strcpy(p_name, pname);
}
CStudent::~CStudent()//析构函数
{
if(p_name)
{
delete [] p_name;
}
}
int main()
{
CStudent stu1("aaa",'f',50,12);
CStudent stu2(stu1);
return 0;
}
|
上一篇: 实用C++课后习题疑惑下一篇: 这是编译器的问题吗?
|