String构造函数

只简单写了几个函数

class String
{
public:
    String(const char* pStr = NULL);
    String(const String& str);
    virtual ~String();
    String &operator =(const String& str);
    int Length() const;
    const char* cstr() const;
    friend std::ostream& operator<<(std::ostream& os, const String& str);

private:
    char* m_pData;
};
String::String(const char* pStr)
{
    if (pStr == NULL)
    {
        m_pData = new char('\0');
    }
    else
    {
        m_pData = new char[strlen(pStr) + 1];
        strcpy(m_pData, pStr);
    }
}

String::String(const String& str)
{
    m_pData = new char[str.Length() + 1];
    strcpy(m_pData, str.cstr());
   //类的成员函数可以直接访问作为其参数的同类型对象的私有成员。
   //即可写为
strcpy(m_pData, str.m_pData);
}

int String::Length() const
{
    return strlen(m_pData);
}

const char * String::cstr() const
{
    return m_pData;
}

String::~String()
{
    if (m_pData)
        delete[] m_pData;
}

String& String::operator =(const String& str)
{
    if (this == &str)
        return *this;

    delete[] m_pData;
    m_pData = new char[str.Length() + 1];
    strcpy(m_pData, str.cstr());

    return *this;
}

std::ostream& operator<<(std::ostream& os, const String& str)
{
    return os << str.cstr();
}
int main()
{
    String s;
    cout << s << endl;

    String s1("hello");
    cout << s1 << endl;

    String s2(s1);
    cout << s2 << endl;


    String s3("hello world");
    cout << s3 << endl;

    s3 = s2;
    cout << s3 << endl;

    String s4 = "lwm";
    cout << s4 << endl;
    
    return 0;
}

 

运行结果:

 

posted @ 2019-03-03 22:27  xslwm  阅读(1337)  评论(0编辑  收藏  举报