构造函数、析构函数与赋值函数
来源:互联网 发布:如何优化宝贝详情页 编辑:程序博客网 时间:2024/05/03 16:42
编写类string 的构造函数、析构函数与赋值函数(25 分)
已知类string 的原型为:
class string
{
public:
string(const char *str = null); // 普通构造函数
string(const string &other); // 拷贝构造函数
~ string(void); // 析构函数
string & operate =(const string &other); // 赋值函数
private:
char *m_data; // 用于保存字符串
};
标准答案:
// string 的析构函数
string::~string(void)
{
delete[] m_data;//由于m_data是内部数据类型,也可以写成delete m_data;
}
//string 的普通构造函数
string::string(const char *str =NULL)
{
if (str == NULL)
{
m_data = new char[1]; // 若能加NULL判断则更好
*m_data = '/0';
}
else
{
int length = strlen(str);
m_data = new char[length + 1]; //若能加上NULL判断则更好
strcpy(m_data, str);
}
}
//拷贝构造函数
string::string(const string &other)
{
int length = strlen(other.m_data);
m_data = new char[length + 1];
strcpy(m_data, other.m_data);
}
//赋值函数
string & string::operate = (const string &other)
{
//检查自赋值
if (this == &other)
return *this;
//释放原有的内存资源
delete []m_data;
//分配新的内存资源,并复制内容
int length = strlen(other.m_data);
m_data = new char[length + 1]; //若能加NULL 判断则更好
strcpy(m_data, other.m_data);
//返回本对象的引用
return *this;
}
- 类的构造函数、析构函数与赋值函数
- 类的构造函数、析构函数与赋值函数
- 类的构造函数、析构函数与赋值函数
- 类的构造函数、析构函数与赋值函数
- 构造函数、析构函数与赋值函数
- 构造函数、析构函数与赋值函数
- 类的构造函数、析构函数与赋值函数
- 类的构造函数、析构函数与赋值函数
- 类的构造函数、析构函数与赋值函数
- 类的构造函数、析构函数与赋值函数
- 类的构造函数、析构函数与赋值函数
- 构造函数、析构函数与赋值函数
- 类的构造函数、析构函数与赋值函数
- 类的构造函数、析构函数与赋值函数
- 类的构造函数、析构函数、与赋值函数
- 类的构造函数,析构函数与赋值函数
- srting的类构造函数、析构函数、拷贝构造函数与赋值构造函数
- 构造函数,拷贝构造函数,赋值函数,析构函数
- 关于:META
- 码元、波特率、比特率、电平、频道带宽等概念的理解
- Oracle9i MERGE语法使用
- 大数阶乘
- Delphi研究之驱动开发篇(一)--实现原理
- 构造函数、析构函数与赋值函数
- vc 自定义菜单编程
- 模块化的大数阶乘
- something wrong with my b2evolution.
- php调用MYSQL的存储过程
- 几个学习Silverlight及Silverlight示例的网站
- 面试笔试系列之二 链表相关
- SAP的我新工作,新生活, 新目标
- 关于在Firefox 3.0添加迅雷下载