【发布时间】:2011-06-14 00:49:33
【问题描述】:
按照我正在阅读的外部 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
3从何而来?
如果我输入:
MyString cMyName("abc");
它只是返回My name is: abc
为什么 3 与Abder-Rahman 一起出现?
谢谢。
【问题讨论】:
-
老兄!你会停止为learncpp.com做广告吗?去拿一本教科书。
-
m_pchString=new char(m_nLength)应该是m_pchString=new char[m_nLength]- 我相信前者至少应该发出编译警告。 -
大声笑,0 票反对,1 个答案和 54 多个问题。你是个水蛭!
-
@Max - 查看 SWE 之前的所有帖子。所有这些都以某种方式链接到 learncpp.com。
-
如果这些教程对您没有帮助,请停止阅读。找点别的。鼓励提出问题,但要求我们解释教程指南的每一页有点过分了。你开始让那些知识最渊博、能为你提供最多帮助的人感到沮丧。展示一些主动性和证据表明您已尝试自己找出这些答案,这将是一种可喜的解脱。否则,您是否拥有该网站?如果是这样,请停止发送垃圾邮件。
标签: c++ constructor