编写类String的构造/析构函数,赋值操作符
2014-05-18 21:39
225 查看
class String { public: String(const char * str = NULL); //普通构造函数 String(const String &other); //复制构造函数 String & operator= (const String &other); //赋值操作符 ~String(); //析构函数 private: char *m_data; }; String::String(const char *str) { if (str == NULL) { m_data = new char[1]; m_data[1] = '\0'; } else { int lenght = strlen(str); m_data = new char[lenght + 1]; strcpy(m_data, str); } } String::String(const String &other) { int lenght = strlen(other.m_data); m_data = new char[lenght + 1]; strcpy(m_data, other.m_data); } String & String::operator= (const String &other) { if(&other == this) //证同测试 return *this; delete [] m_data; int lenght = strlen(other.m_data); m_data = new char[lenght + 1]; strcpy(m_data, other.m_data); return *this; //第一次写的时候忘记返回*this } String & String::operator= (const String &other) { String temp(other); // delete [] m_data; swap(m_data, other.m_data); return *this; //又忘记返回*this } String::~String() { delete [] m_data; }
相关文章推荐
- 编写类String的构造函数、析构函数和赋值操作符
- 编写合适的构造函数、拷贝构造函数、赋值操作符、析构函数(后三者一般同时出现,称为“大三元法则”),那么这个概念就完整并且不用再考虑其资源(内存)管理的问题。
- 实现string的默认构造函数,拷贝函数,c型字符串参数的构造函数,赋值构造函数,析构函数,重载输出操作符,测试
- String的构造,析构,赋值,赋值函数编写
- C++:析构函数、对象生命周期、类型转换构造、拷贝构造、拷贝赋值、深浅拷贝
- 编写类String的构造函数、析构函数和赋值函数
- 编写类String的构造函数、析构函数和赋值函数
- 继承中,构造函数,赋值操作符,析构函数与虚函数的关系
- 构造函数和析构函数,拷贝构造,赋值重载,调用练习
- String拷贝,构造和析构函数.
- 编写类String 的构造函数、析构函数和赋值函数
- 编写类String 的构造函数、析构函数和赋值函数
- 编写类String的构造函数、析构函数和赋值函数。
- boolan第二周笔记:构造函数、拷贝构造、赋值构造、析构函数
- C++在单继承、多继承、虚继承时,构造函数、复制构造函数、赋值操作符、析构函数的执行顺序和执行内容
- string的四个函数--构造、析构、拷贝、赋值
- 编写类String的构造函数、析构函数和赋值函数(转载)
- 编写类String的构造函数、析构函数和赋值函数
- Java中用字符串常量赋值和使用new构造String对象的区别
- 编写类String的构造函数、析构函数和赋值函数