我正在创建自己的字符串类,但是在使用strlen()执行此操作时,我在读取字符串的字符时遇到了问题。
/****str.h****/
class str
{
private:
char *m_ptr;
unsigned int m_size;
//unsigned int m_capacity;
public:
str();
str (const char *);
str (const str &);
~str (){if (m_size != 0) delete [] m_ptr;};
char *data() {return m_ptr;};
//Sobrecarga de operadors.
str operator=(str);
friend std::ostream& operator<<(std::ostream &, str);
};
我使用用c-string常量初始化的构造函数得到了错误。
/****str.cpp****/
//Default constructor.
str :: str ()
{
m_ptr = new char [1];
m_ptr[0] = '\0';
m_size = 0;
//m_capacity = 10;
}
str :: str(const char *sm_ptr)
{
m_size = strlen(sm_ptr); //HERE IS WHERE THE ERROR OCCURS.
m_ptr = new char[m_size + 1];
strcpy(m_ptr, sm_ptr); //Copies the C string pointed by source into the array pointed by destination, including the terminating null character
}
//Copy constructor.
str :: str(const str &right)
{
m_ptr = new char [right.m_size];
strcpy (m_ptr, right.m_ptr);
m_size = right.m_size;
}
str str::operator=(str right)
{
if (m_size != 0) delete [] m_ptr;
m_ptr = new char [right.m_size + 1];
strcpy(m_ptr, right.m_ptr);
m_size = right.m_size;
return *this;
}
std::ostream &operator<<(std::ostream &strm, str obj)
{
strm << obj.m_ptr;
return strm;
}
0x0053fdd0 {m_ptr = 0xcccccccc m_size = 3435973836} str *
答案 0 :(得分:1)
将赋值运算符声明更改为
str& operator=(str&);
甚至
const str& operator=(const str&);
将消除临时对象的创建。查看this article以获取有关将参数传递给函数的更多信息。
还有其他一些问题。例如,在默认构造函数中,您可以分配内存但不必设置大小,因此永远不会释放内存。此外,在复制构造函数和赋值运算符中,检查自我赋值几乎总是一个好主意。