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;
}

 

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM