#include
#include
class CStudent
{
public:
CStudent(char *n, int a);
~CStudent();
private:
char *name;
int age;
};
CStudent::CStudent(char *n, int a)
:age(a)
{
int nLen = strlen(n);
name = new char[nLen+1];
strcpy(name,n);
name[nLen] = '\0';
}
CStudent::~CStudent()
{
delete[] name;
}
class CTeacher
{
public:
CTeacher(char *tn, int ta);
~CTeacher();
void SetStuAge(int a);
private:
char *name;
int age;
CStudent stu;
};
CTeacher::CTeacher(char *tn, int ta)
:age(ta)
{
int nLen = strlen(tn);
name = new char[nLen+1];
strcpy(name,tn);
name[nLen] = '\0';
}
CTeacher::~CTeacher()
{
delete[] name;
}
void CTeacher::SetStuAge(int a)
{
stu.age = a;
}
void main()
{
CStudent stu("张三",25);
CTeacher tea("李四",26);
}
#include <iostream.h>
#include <string.h>
class CStudent
{
public:
CStudent(char *n, int a);
CStudent() { name=new char[100];}
~CStudent();
int age;
private:
char *name;
};
CStudent::CStudent(char *n, int a)
:age(a)
{
int nLen = strlen(n);
name = new char[nLen+1];
strcpy(name,n);
name[nLen] = '\0';
}
CStudent::~CStudent()
{
delete[] name;
}
class CTeacher
{
public:
CTeacher(char *tn, int ta);
~CTeacher();
void SetStuAge(int a);
private:
char *name;
int age;
CStudent stu;
};
CTeacher::CTeacher(char *tn, int ta)
:age(ta)
{
int nLen = strlen(tn);
name = new char[nLen+1];
strcpy(name,tn);
name[nLen] = '\0';
}
CTeacher::~CTeacher()
{
delete[] name;
}
void CTeacher::SetStuAge(int a)
{
stu.age = a;
}
int main()
{
char s1[] = "张三";
char s2[] = "李四";
CStudent stu(s1,25);
CTeacher tea(s2,26);
}
首先,将name初始化为0 : 一个普通的类成员不显式初始化就会被初始化为一个随机值,那么未指向任何有意义空间的指针如果不被置为 0 ,之后使用时天知道它指向的空间是否有效,并且对于动态内存来说,释放也成了一个问题
其次,考虑深拷贝 : 对于类成员有指针,并且这个指针用来指向一片动态申请的空间的情形,请考虑使用深拷贝,需重写复制构造函数和赋值操作符,否则默认的拷贝函数或者赋值操作(浅拷贝)会引起多个指针指向同一个空间的情形,由于你的程序本身考虑到了对动态空间的释放问题,那么多次释放同一空间,会引起段错误。
e,抱歉,之前指出的问题在你这个程序中还体现不出来,你遇到的编译错误是 CTeacher tea("李四",26); 的错误,原因是在CTeacher的构造函数中会初始化成员CStudent stu,而在CTeacher的构造函数中你没有显式地初始化stu,那么会自动调用CStudent::CStudent()这个CStudent的构造函数,但显然CStudent中没有这个构造函数
解决方式:
(1) 为CStudent添加无参构造函数
(2)显式初始化CStudent,如
CTeacher::CTeacher(char *tn, int ta)
:age(ta), stu("张三",25)
{
int nLen = strlen(tn);
name = new char[nLen+1];
strcpy(name,tn);
name[nLen] = '\0';
}