String拷贝,构造和析构函数.
2010-12-10 14:57
127 查看
class String
{
public:
String(const char *str = NULL); // 普通构造函数
String(const String &other); // 拷贝构造函数
String & operator =(const String &other); // 赋值函数
~ String(void); // 析构函数
private:
char *m_data; // 用于保存字符串
};
// String的普通构造函数
String::String(const char *str)
{
if(str==NULL)
{
m_data = new char[1];
*m_data = '\0';
}
else
{
int length = strlen(str);
m_data = new char[length+1];
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::operator =(const String &other)
{
if(this == &other) // (1) 检查自赋值
return *this;
delete [] m_data; // (2) 释放原有的内存资源
int length = strlen(other.m_data); // (3)分配新的内存资源,并复制内容
m_data = new char[length+1]; // 若能加 NULL 判断则更好
strcpy(m_data, other.m_data); // (4)返回本对象的引用
return *this;
}
// String的析构函数
String::~String(void)
{
delete [] m_data; // 由于m_data是内部数据类型,也可以写成 delete m_data;
}
{
public:
String(const char *str = NULL); // 普通构造函数
String(const String &other); // 拷贝构造函数
String & operator =(const String &other); // 赋值函数
~ String(void); // 析构函数
private:
char *m_data; // 用于保存字符串
};
// String的普通构造函数
String::String(const char *str)
{
if(str==NULL)
{
m_data = new char[1];
*m_data = '\0';
}
else
{
int length = strlen(str);
m_data = new char[length+1];
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::operator =(const String &other)
{
if(this == &other) // (1) 检查自赋值
return *this;
delete [] m_data; // (2) 释放原有的内存资源
int length = strlen(other.m_data); // (3)分配新的内存资源,并复制内容
m_data = new char[length+1]; // 若能加 NULL 判断则更好
strcpy(m_data, other.m_data); // (4)返回本对象的引用
return *this;
}
// String的析构函数
String::~String(void)
{
delete [] m_data; // 由于m_data是内部数据类型,也可以写成 delete m_data;
}
相关文章推荐
- string 构造 拷贝 和析构函数
- big three三大函数:拷贝构造拷贝赋值析构函数
- 三大函数:拷贝构造,拷贝赋值,析构函数
- 号)、sex(性别)、birthday(出生日期)、id(身份证号)等等。其中“出生日期”定义为一个“日期”类内嵌子对象。用成员函数实现对人员信息的录入和显示。要求包括:构造函数和析构函数、拷贝构造函
- 编写类String的构造/析构函数,赋值操作符
- C++:复数类构造函数、拷贝构造、运算符重载、析构函数
- 拷贝构造,深度拷贝,关于delete和default相关的操作,explicit,类赋初值,构造函数和析构函数,成员函数和内联函数,关于内存存储,默认参数,静态函数和普通函数,const函数,友元
- 类的默认成员函数,构造函数,拷贝构造,析构函数,赋值运算符重载
- c++ primer 13.13练习(构造,拷贝,析构函数何时发生详解)
- C++【面试题】:类实现万年历(日期计算器),(含构造函数、拷贝构造、运算符重载、析构函数)
- C++【面试题】:类实现万年历(日期计算器),(含构造函数、拷贝构造、运算符重载、析构函数)
- C++基础-构造函数/析构函数/拷贝构造
- 类 构造 析构函数 调用顺序/ 复制(拷贝)构造&&赋值函数
- C++:复数类构造函数、拷贝构造、运算符重载、析构函数
- GeekBand学习笔记:C++三大函数:拷贝构造、拷贝赋值、析构函数
- boolan第二周笔记:构造函数、拷贝构造、赋值构造、析构函数
- 深入了解构造函数,析构函数,拷贝构造,赋值函数的原理
- C++之构造函数,拷贝构造,析构函数
- string的四个函数--构造、析构、拷贝、赋值
- C++类的构造、拷贝构造、析构函数等