string函数的构造函数,析构函数,拷贝构造,赋值构造
2017-10-27 19:16
197 查看
#include<iostream> using namespace std; #include<assert.h> class String { public: String(const char *str = NULL); String(const String& other); String& operator=(const String & other); ~String(void); void print() { cout<<m_data<<endl; } private: char* m_data; }; String::String(const char *str) { if(str == NULL) { m_data = new char[1]; assert(m_data != NULL); *m_data = '\0'; } else { int length = strlen(str); m_data = new char[length+1];//特别重要,否则会造成程序奔溃; assert(m_data != NULL); strcpy(m_data,(char*)str); } } String::String(const String& other) { int length = strlen(other.m_data); m_data = new char[length+1];//一定要多加1; assert(m_data!=NULL); strcpy(m_data,other.m_data); } String& String::operator=(const String& other) { if(this != &other) { delete []m_data; int length = strlen(other.m_data); m_data = new char[length+1];//一定要多加1; assert(m_data != NULL); strcpy(m_data,other.m_data); } return *this; } String::~String(void) { delete []m_data; m_data = NULL; } int main() { String sr("abcd"); String s = sr; String sc = "befe";//调用的是构造函数; sc =sr; sr.print(); s.print(); sc.print(); }
相关文章推荐
- C++【面试题】:类实现万年历(日期计算器),(含构造函数、拷贝构造、运算符重载、析构函数)
- C++基础-构造函数/析构函数/拷贝构造
- 深入了解构造函数,析构函数,拷贝构造,赋值函数的原理
- 深度解析-->c++中构造函数,拷贝构造,赋值运算符重载,析构函数的调用情况
- 构造函数和析构函数,拷贝构造,赋值重载,调用练习
- 拷贝构造,构造函数,析构函数的调用顺序
- 构造函数和析构函数,拷贝构造,赋值重载,调用练习
- 构造函数,拷贝构造,析构函数,运算符重载。
- C++之构造函数,拷贝构造,析构函数
- 类的默认成员函数,构造函数,拷贝构造,析构函数,赋值运算符重载
- C++之构造函数,拷贝构造,析构函数再剖析
- 拷贝构造,深度拷贝,关于delete和default相关的操作,explicit,类赋初值,构造函数和析构函数,成员函数和内联函数,关于内存存储,默认参数,静态函数和普通函数,const函数,友元
- C++ 构造函数、析构函数、拷贝构造、赋值运算符
- 号)、sex(性别)、birthday(出生日期)、id(身份证号)等等。其中“出生日期”定义为一个“日期”类内嵌子对象。用成员函数实现对人员信息的录入和显示。要求包括:构造函数和析构函数、拷贝构造函
- boolan第二周笔记:构造函数、拷贝构造、赋值构造、析构函数
- C++【面试题】:类实现万年历(日期计算器),(含构造函数、拷贝构造、运算符重载、析构函数)
- C++拷贝构造和赋值构造
- 《深度探索C++对象模型》笔记(三)构造函数、拷贝构造和初始化列表
- C++拾遗--构造函数(二)拷贝构造
- Big-Five: 析构函数,拷贝构造函数,移动构造函数,拷贝赋值操作和移动赋值操作