life02

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  197 随笔 :: 3 文章 :: 37 评论 :: 0 Trackbacks

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=sizeof(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();


}

posted on 2009-09-14 09:35 life02 阅读(6462) 评论(4)  编辑 收藏 引用 所属分类: c++学习

评论

# re: 类string的构造函数、拷贝构造函数和析构函数 2009-10-23 11:18 zhhao
String& String::operator =(const String &other)
int length=sizeof(other.m_data);
这行错了吧。。。。  回复  更多评论
  

# re: 类string的构造函数、拷贝构造函数和析构函数[未登录] 2010-11-17 10:21 ocean
m_data 访问属性为私有的,可以直接访问吗?
碰到好多面试题,都这样,是不是错了?  回复  更多评论
  

# re: 类string的构造函数、拷贝构造函数和析构函数 2011-03-01 15:57 jayden
确实
String& String::operator =(const String &other)
int length=sizeof(other.m_data);
这行 length的值是指针的大小,4字节  回复  更多评论
  

# re: 类string的构造函数、拷贝构造函数和析构函数[未登录] 2011-03-07 14:47 C
@ocean
这是类里面的方法  回复  更多评论
  


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理