编写类String 的构造函数、析构函数和赋值函数
来源:互联网 发布:js 展开所有树节点 编辑:程序博客网 时间:2024/06/06 07:50
转:http://blog.csdn.net/zhuimengzh/article/details/6708882
编写类String 的构造函数、析构函数和赋值函数,已知类String 的原型为:
class String
{
public:
String(const char *str = NULL); // 普通构造函数
String(const String &other); // 拷贝构造函数
~ String(void); // 析构函数
String & operate =(const String &other); // 赋值函数
private:
char *m_data; // 用于保存字符串
};
- #include <iostream>
- class String
- {
- public:
- String(const char *str=NULL);//普通构造函数
- String(const String &str);//拷贝构造函数
- String & operator =(const String &str);//赋值函数
- ~String();//析构函数
- protected:
- private:
- char* m_data;//用于保存字符串
- };
- //普通构造函数
- String::String(const char *str){
- if (str==NULL){
- m_data=new char[1]; //对空字符串自动申请存放结束标志'\0'的空间
- if (m_data==NULL){//内存是否申请成功
- std::cout<<"申请内存失败!"<<std::endl;
- exit(1);
- }
- m_data[0]='\0';
- }
- else{
- int length=strlen(str);
- m_data=new char[length+1];
- if (m_data==NULL){//内存是否申请成功
- std::cout<<"申请内存失败!"<<std::endl;
- exit(1);
- }
- strcpy(m_data,str);
- }
- }
- //拷贝构造函数
- String::String(const String &str){ //输入参数为const型
- int length=strlen(str.m_data);
- m_data=new char[length+1];
- if (m_data==NULL){//内存是否申请成功
- std::cout<<"申请内存失败!"<<std::endl;
- exit(1);
- }
- strcpy(m_data,str.m_data);
- }
- //赋值函数
- String& String::operator =(const String &str){//输入参数为const型
- if (this==&str) //检查自赋值
- return *this;
- int length=strlen(str.m_data);
- delete [] m_data;//释放原来的内存资源
- m_data= new char[length+1];
- if (m_data==NULL){//内存是否申请成功
- std::cout<<"申请内存失败!"<<std::endl;
- exit(1);
- }
- strcpy(m_data,str.m_data);
- return *this;//返回本对象的引用
- }
- //析构函数
- String::~String(){
- delete [] m_data;
- }
- void main(){
- String a;
- String b("abc");
- system("pause");
- }
0 0
- 编写类String的构造函数、拷贝构造函数、析构函数和赋值函数
- 编写类String 的构造函数、拷贝构造函数、析构函数和赋值函数
- 网易游戏笔试题:编写string类的构造函数、拷贝构造函数、赋值构造函数和析构函数
- 编写类String的构造函数、析构函数和赋值函数
- 编写类String的构造函数,析构函数和赋值函数
- 编写类String的构造函数、析构函数和赋值函数
- 编写类String的构造函数、析构函数和赋值函数
- 编写类String 的构造函数、析构函数和赋值函数
- 编写类String的构造函数、析构函数和赋值函数
- 如何正确编写类String的构造函数、析构函数和赋值函数
- 编写类String的构造函数、析构函数和赋值函数
- 编写类String的构造函数、析构函数和赋值函数
- 编写类String的构造函数、析构函数和赋值函数
- 编写类String的构造函数、析构函数和赋值函数
- 编写类String 的构造函数、析构函数和赋值函数
- 编写类String的构造函数、析构函数和赋值函数
- 编写类String的构造函数、析构函数和赋值函数
- 编写类String的构造函数、析构函数和赋值函数
- 随机验证码(线条,旋转,干扰线)
- 简化PHP开发的10个工具
- 启用QNX系统,海尔智能冰箱或成业界“宝马”
- typedef函数指针用法 assert()
- JavaScript Scope( 作用域 ) , Scope chain( 作用域链 )
- 编写类String 的构造函数、析构函数和赋值函数
- myEclipse2014 python开发环境搭建
- RMAN 备份恢复
- 按值传递的
- 控制台下实现简单的线程同步--事件
- 【高中生物】基因工程核心知识点
- undefined reference to
- 深入理解const char*p,char const*p,char *const p,const
- 搜索进化让智能硬件无界