2014-07-08 28 views
-5

我正在创建自己的字符串类,但在使用strlen()来读取字符串的字符时遇到了问题。我的str类错误

/****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字符串常量初始化的构造函数。

/****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 *

+3

欢迎来到Stack Overflow。请阅读[Stack Overflow:How to ask](http://stackoverflow.com/questions/how-to-ask)和[Jon Skeet的问题清单](http://msmvps.com/blogs/jon_skeet/archive/2012) /11/24/stack-overflow-question-checklist.aspx)来找出如何提出一个很好的问题,这将产生很好的答案。 –

+0

_'I使用了''错误,特别是哪个错误?请编辑你的问题。 –

回答

1

改变赋值操作符声明

str& operator=(str&); 

甚至

const str& operator=(const str&); 

将消除临时对象的创建。有关将参数传递给函数的更多信息,请参阅this article

还有一些其他问题。例如,在默认构造函数中,您分配内存,但不设置大小,因此永远不会释放内存。另外,在复制构造函数和赋值运算符中,检查自赋值几乎总是一个好主意。

相关问题