class中缺省的4个函数的实现

原文链接

class类中默认会实现4个函数,分别为默认构造函数,拷贝构造函数,析构函数和=运算符重载

 

#include <iostream>
using namespace std;
class myString
{
    public:
        myString(const char *str=NULL);
        myString(const myString &other);
        ~myString();
        myString & operator=(const myString &other);
        showString();
    private:
        char *m_data;
        
};

myString::~myString()
{
    delete [] m_data;
}
myString::myString(const char *str)
{
    if (str == NULL)
    {
        m_data = new char[1];
        *m_data = '\0';
    } 
    else
    {
        int length = strlen(str)+1;
        m_data = new char[length];
        while(*str != '\0')
            *m_data++ = *str++;
        *m_data = '\0';
    }        
}
myString::myString(const myString &other)
{
    int length = strlen(other.m_data)+1;
    m_data = new char(length);
    strcpy(m_data,other.m_data);
    *m_data = '\0';
}
myString & myString::operator=(const myString &other)
{
    if (this == &other)
    {
        return *this;
    } 
    delete []m_data;
    int length = strlen(other.m_data)+1;
    m_data = new char[length];
    strcpy(m_data,other.m_data);
    return *this;
}
myString::showString()
{
    cout<<this->m_data<<endl;
}
int main(int argc,char **argv)
{
    myString str;
    char *p = "hello peter";
    myString dest(p);
    dest.showString();
    str = dest;
    str.showString();
    return 0;
}
posted @ 2012-05-28 13:42  wangkangluo1  阅读(665)  评论(0编辑  收藏  举报