以下是我正在閱讀的外部C++學習資源的示例。C++ - 奇怪的輸出
主要內容如下:
#include <iostream>
#include <cstring>
class MyString
{
private:
char *m_pchString;
int m_nLength;
public:
MyString(const char *pchString="")
{
//find the length of the string
//plus "1" for a terminator
m_nLength=strlen(pchString)+1;
//allocate a buffer equal to this length
m_pchString=new char(m_nLength);
//copy the parameter into our internal buffer
strncpy(m_pchString,pchString,m_nLength);
//make sure the string is terminated
m_pchString[m_nLength-1]='\0';
}
~MyString() //destructor
{
//deallocate buffer
delete m_pchString;
//set m_pchString to null just in case
//m_pchString=0;
}
char* GetString()
{
return m_pchString;
}
int GetLength()
{
return m_nLength;
}
};
int main()
{
MyString cMyName("Abder-Rahman");
std::cout<<"My name is: "<<cMyName.GetString()<<std::endl;
return 0;
} //cMyName destructor is called here
輸出是:My name is: Abder-Rahman3
哪兒了來自?
如果鍵入:
MyString cMyName("abc");
它只是簡單地返回My name is: abc
爲什麼出現與Abder-Rahman
?
謝謝。
老兄!你會停止廣告learncpp.com。去拿一本教科書。 – Neo 2011-01-23 13:53:43