类string的构造函数、拷贝构造函数和析构函数
来源:互联网 发布:工具制作软件 编辑:程序博客网 时间:2024/05/29 19:20
编写类String的构造函数、拷贝构造函数、析构函数和赋值函数
一、题目:
class String{public: String(const char *str = NULL); // 普通构造函数 String(const String &other); // 拷贝构造函数 ~String(void); // 析构函数 String & operator = (const String &other); // 赋值函数private: char *m_data; // 用于保存字符串};
各个解析:
1、构造函数
/*
1、构造函数在构造对象时使用;
2、传入参数的判断;
3、对象的初始化问题。
*/
String::String(const char *str){ if ( NULL == str) { m_data = new char[1] *m_data = '\0'; } else { int len = strlen(str); m_data = new char[len + 1]; strcpy(m_data,str); }}
2、拷贝构造函数
/*
1、拷贝构造函数必须在构造对象时使用,即定义对象时;
2、对象初始化问题。
*/
String::String(const String &other){ int len = strlen(other.m_data); m_data = new char[len+1]; strcpy(m_data,other.m_data);}
3、赋值函数
/*
1、赋值函数使用时,对象肯定已经建立;
2、赋值前,判断是否是自我赋值;
3、赋值前,内存空间的准备:
由于赋值前,对象已占有一定大小内存,但是赋值对象所占内存大小与
对象已占的内存大小不一定一致;
先释放对象已占的内存,然后分配心内存。
4、正常赋值
*/
String & String::operator = (const String &other){ if (&other == this) { return *this; } delete [] m_data; int len = strlen(other.m_data); m_data = new char[len+1]; strcpy(m_data,other.m_data); return *this;}
4、析构函数
/*
资源的释放
*/
String::~String(void){ delete []m_data;}
5、拷贝构造函数与赋值函数相关知识
1、 拷贝构造函数与赋值函数的区别?
在看到“=”操作符为对象赋值的时候,
如果是在对象定义时(Test B = (Test)c),此时调用拷贝构造函数;
如果不是在对象定义赋值时(B = c),此时调用赋值函数。
注:构造函数、拷贝构造函数,带有构造两个字,顾名思义,就是在对象声明或定义时才会使用。
2、拷贝构造函数与赋值函数定义的区别?
内存空间角度:
1)拷贝构造函数的使用,是在建立对象时;当时对象没有占有内存,故不需要释放内存,不重新建立内存空间。
2)赋值函数的使用,是在对象建立后;当时对象已经占有内存,故需要释放先前内存,然后重新获取内存空间。
阅读全文
0 0
- string类的构造函数,析构函数,拷贝构造函数和赋值构造函数
- string类的构造函数,拷贝构造函数,析构函数和赋值函数
- String类的构造函数,析构函数,拷贝构造函数和赋值函数
- string类的构造函数,拷贝构造函数,析构函数和赋值函数
- 编写类String的构造函数、拷贝构造函数、析构函数和赋值函数
- string类的构造函数、析构函数、拷贝构造函数和赋值函数
- 编写类String 的构造函数、拷贝构造函数、析构函数和赋值函数
- 写String类的普通构造函数,析构函数,拷贝构造函数和赋值函数
- 编写类string的构造函数、拷贝构造函数和析构函数
- 类string的构造函数、拷贝构造函数和析构函数
- 类String的构造函数拷贝构造函数和析构函数
- 类string的构造函数、拷贝构造函数和析构函数
- 类string的构造函数、拷贝构造函数和析构函数
- 类string的构造函数、拷贝构造函数和析构函数
- 类string的构造函数、拷贝构造函数和析构函数
- C++面试之 类string的构造函数、拷贝构造函数和析构函数
- 网易游戏笔试题:编写string类的构造函数、拷贝构造函数、赋值构造函数和析构函数
- String的构造函数,拷贝构造函数、析构函数和赋值函数
- OpenCV—直线拟合fitLine
- ubuntu 14.04 源列表
- [深度学习]降噪自动编码器
- Python程序bug记录,不定时更新ing~~~~
- [关于OPC的研究1]c# opc client源码调试和学习笔记
- 类string的构造函数、拷贝构造函数和析构函数
- python: delattr函数
- redis,java释放资源正确方式,防止redis因resource的异常
- pcl--不同格式点云的转换
- 疯牛
- Gradle 完整指南(Android)
- 剑指offer 二维有序数组查找
- 如何使用gcc编译静态库和动态库?以及如何使用?
- 点亮细胞1-10