2013-06-19 147 views
-8
#include<iostream> 
    #include<string.h> 
    using namespace std; 

class MyString 
{ 
private: 
    char *m_pchString; 
    int m_nLength; 

public: 
    MyString(const char *pchString="")   // explain this 
    { 
     m_nLength = strlen(pchString) + 1; 

     m_pchString = new char[m_nLength];  // explain this 

     strncpy(m_pchString, pchString, m_nLength); 

     m_pchString[m_nLength-1] = '\0'; 
    } 

    ~MyString() 
    { 
     delete[] m_pchString; 

     m_pchString = 0; 
    } 

    char* GetString() { return m_pchString; } // explain this 
    int GetLength() { return m_nLength; } 
}; 


int main() 
{ 
    MyString cMyName("Alex"); 
    cout << "My name is: " << cMyName.GetString() << endl; 
    return 0; 
} 

爲什麼在這個新的運算符中使用....我瞭解了大部分,但我很困惑爲什麼char指針被分配一個數組使用new運算符....?這是一個C++代碼.....請幫我理解這段代碼

回答

0
MyString(const char *pchString="") 

MyString類的構造與[可選]參數具有的char*如此類型,MyString str;將是有效的。

m_pchString = new char[m_nLength]; 

m_pchString是一個原始指針。在這個實現中,它指向garbage address(?)(在C++編譯器中不確定原因,指針未初始化爲NULL)。它需要在堆上分配第一個資源。如果處理不當,危險使用。

char* GetString() { return m_pchString; } 

它返回的m_pchString的基地址,這樣你可以在以下地址m_pchString的指向訪問,並在找到0

+0

另請注意,GetString的返回值不是'const'。可以改變'MyString'之外的緩衝區,這與數據封裝的想法相矛盾。 – urzeit

1

運算符new(它實際上是 - new[] -Operator)用於獲取具有m_nLength元素的char數組。 delete[]析構函數中的操作符用於釋放內存。

+6

而[無效複製語義(HTTP停止: //stackoverflow.com/questions/4172722)是用來讓你玩得很開心的調試會話。 –

+0

@Mike Seymour想說的是,實現拷貝構造函數也是一個好主意,因爲'MyString'實例的副本將使用與原始相同的緩衝區,這可能會導致未解決的結果。如果您隨後銷燬其中一個對象,則在使用另一個對象時很可能會出現段錯誤,因爲指針將指向無效內存(即由副本的析構函數釋放)。 – urzeit

+0

和一個複製賦值運算符。並移動這些版本。 – chris