2011-03-16 92 views
1

我想重新學習C++,並想知道是否有人可以幫我在這裏。我試圖實現我自己的String類來查看我是否可以記住事情,但我被卡在構造函數中。C++:如何實現自己的String類?

我有我的頭文件,並希望有一個構造函數這樣:

頭文件(MYFILES \ STRING.H):

#ifndef STRING_ 
#define STRING_ 

using namespace std; 
#include <iostream> 

class String 
{ 
    private: 

    static const unsigned int MAX = 32; // Capacity of string 

    char Mem[MAX]; // Memory to hold characters in string 
    unsigned Len;  // Number of characters in string 

    public: 

    // Construct empty string 
    // 
    String() 
    { 
     Len = 0; 
    } 

    // Reset string to empty 
    // 
    void reset() 
    { 
     Len = 0; 
    } 

    // Return status information 
    // 
    bool empty() const 
    { 
     return Len == 0; 
    } 

    unsigned length() const 
    { 
     return Len; 
    } 

    // Return reference to element I 
    // 
    char& operator[](unsigned I) 
    { 
     return Mem[I]; 
    } 

    // Return constant reference to element I 
    // 
    const char& operator[](unsigned I) const 
    { 
     return Mem[I]; 
    } 

    // Construct string by copying existing string 
    // 
    String(const String&); 

    // Construct string by copying array of characters 
    // 
    String(const char []); 

    // Copy string to the current string 
    // 
    String& operator=(const String&); 

    // Append string to the current string 
    // 
    String& operator+=(const String&); 
}; 

// Compare two strings 
// 
bool operator==(const String&, const String&); 
bool operator!=(const String&, const String&); 

// Put a string into an output stream 
// 
ostream& operator<<(ostream&, const String&); 

#endif 

我卡上的位是這樣的:

String::String(const String& str) 
{ 
    //what goes here? 
} 

謝謝!

+5

世界真的是沒有另一個字符串類更好... – 2011-03-16 23:21:27

+6

@Kornel:演習的重點是學習,而不是取代的std :: string。 – 2011-03-16 23:24:30

回答

2

那麼,因爲它是一個學習練習。

我想你想拷貝另一個字符串的內容,因爲這是一個拷貝構造函數。所以你會想複製所有的成員變量。在你的情況 複製構造函數是沒有必要的,因爲你有一個靜態數組。如果你有 動態內存(即用新分配指向內存的指針),那麼你需要這個。然而, 告訴你它是如何完成的,在這裏你去。

String::String(const String& str) 
{ 
    //what goes here? 
    assert(str.Len < MAX); // Hope this doesn't happen. 
    memcpy(Mem, str.Mem, str.Len); 
    Len = str.Len; 
} 
+1

我應該澄清,有一個默認複製構造函數定義,默認情況下複製所有成員變量。如果你有動態內存,那麼你需要定義一個拷貝構造函數。 – Matt 2011-03-16 23:33:06

+2

+1,這就是我要說的,雖然我會強調一個關鍵點 - 當默認設置已經做對了的時候,不要實現複製ctor或複製賦值操作符。有一種可能的優化,即只複製'Len'字節可以爲短字符串保存一些複製,但32字節是不夠的,我不會擔心。 – 2011-03-16 23:38:01

1

您需要將str中的數據複製到this。長度很簡單:

Len = str.Len; // or, equiv. this->Len= str.Len 

數據有點難。您可能使用strcpymemcpy,或甚至使用for循環。

memcpy(Mem, str.Mem, sizeof Mem); 

祝你好運!

+0

小問題,memcpy複製整個mem數組,包括那些不屬於字符串但在數組中的Len以外的數組。 – Matt 2011-03-16 23:36:52

0

我同意Kornel Kisielewicz:手卷字符串類越少越好。但是你只是在學習,所以這麼公平:-)。無論如何:你的拷貝構造函數需要拷貝Mem數組的長度和內容,就是這樣。 (如果你這樣做是爲了做一些有用的事情而不是學習練習,我會添加:具有固定的最大字符串長度的字符串類 - 特別是一個小至32個字符的字符串類 - 是非常糟糕的但如果你不想在處理內存分配和釋放的同時嘗試記住更基本的內存,那麼這是完全合理的......)