以下是我正在阅读的外部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