类string的构造函数、拷贝构造函数和析构函数

来源:互联网 发布:环境破坏的资料数据 编辑:程序博客网 时间:2024/06/06 03:34

可用于探究 c++ 语言的一些特性:RVO,格式化,可变参数列表,等等,很好的试验原材料

引用http://www.cppblog.com/life02/archive/2011/03/07/96085.html  在这个帖子的基础上稍微添加修改了点内容。

String 类的原型如下

class String
{
   public:
          String(const char *str=NULL); //构造函数
          String(const String &other); //拷贝构造函数
          ~String(void); //析构函数
          String& operator=(const String &other); //等号操作符重载

          ShowString();


   private:
          char *m_data; //指针
};


String::~String()
{
    delete [] m_data; //析构函数,释放地址空间
}
String::String(const char *str)
{
    if (str==NULL)//当初始化串不存在的时候,为m_data申请一个空间存放'\0';
     {
        m_data=new char[1];
        *m_data='\0';
     }
    else//当初始化串存在的时候,为m_data申请同样大小的空间存放该串;
     {
        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 [length+1];
    strcpy(m_data,other.m_data);
}
String& String::operator =(const String &other) 
{
    if (this==&other)//当地址相同时,直接返回;
        return *this; 
 
    delete [] m_data;//当地址不相同时,删除原来申请的空间,重新开始构造;

    int length= strlen (other.m_data);
    m_data=new [length+1];
    strcpy(m_data,other.m_data);

    return *this; 
}

String::ShowString()//由于m_data是私有成员,对象只能通过public成员函数来访问;

{

         cout<<this->m_data<<endl;

}

main()
{
String AD;
char * p="ABCDE";
String B(p);
AD.ShowString();
AD=B;
AD.ShowString();

}

1. strCopy 函数可以为标准库函数 char *strcpy(char *dest, const char *src); 

    需要#inculde <string.h>

2.参考连接:

   高质量C++C编程指南 http://man.chinaunix.net/develop/c&c++/c/c.htm

    字符串函数 http://www.ggv.com.cn/forum/clib/string/strcpy.html

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 怀孕四个月睡眠不好怎么办 二胎七个月肚子太大怎么办 上火牙疼牙龈肿怎么办 孕30周乳房胀痛怎么办 怀孕长妊娠纹了怎么办 坐久了肚子胀疼怎么办 怀孕后胖的太快怎么办 怀孕牙齿全坏了怎么办 怀孕脸胖了好多怎么办 孕晚期不爱吃肉怎么办 怀孕期间胖了怎么办啊 孕期长得太胖怎么办 狗吃马肉脸肿了怎么办 狗过敏了脸肿了怎么办 孕初期外阴很痒怎么办 怀孕了吃了田鸡怎么办 孕妇睡眠质量差怎么办吃什么 39周2天了还不生怎么办 孕中期体重猛长怎么办 4个半月胎位不正怎么办 41周不产生宫缩怎么办 生完孩子胎盘没有脱落怎么办 39周还是臀位怎么办 怀孕7个月胎位不正怎么办 怀孕六个多月胎位不正怎么办 怀孕七个月了胎位不正怎么办 怀孕七个月胎位不正怎么办 怀孕肚子上有妊娠纹怎么办 怀孕九个月肚子长痱子怎么办 怀孕前体重偏胖怎么办 怀孕打胰岛素血糖控制不好怎么办 孕后期憋的难受怎么办 怀孕6个月不想生怎么办 孕六个月不想要怎么办 怀孕9个月喝酒了怎么办 怀孕8个月喝醉了怎么办 怀孕6个月胃酸烧心怎么办 怀孕7个月胃酸怎么办 怀孕5个月胃酸怎么办 怀孕2个月胃酸怎么办 怀孕六个月胃酸烧心怎么办