一个string类,笔试中常遇到的:
/**************************************** * * * * ***************************************/
#ifndef __MYSTRING_H__ #define __MYSTRING_H__
#include <unistd.h> #include <string.h> #include <stdio.h>
class mystring { private: char *m_data; protected: public: mystring(const char *p = NULL); mystring(const mystring &other); ~mystring(void); mystring &operator=(const mystring &other); };
mystring::mystring(const char *p) { printf("normal constructor.\n"); if(p == NULL) { m_data = new char[1]; m_data[0] = '\0'; } else { int len = strlen(p); m_data = new char[len+1]; strcpy(m_data, p); } }
mystring::mystring(const mystring &other) { printf("copy constructor.\n"); int len = strlen(other.m_data); m_data = new char[len]; strcpy(m_data, other.m_data); }
mystring &mystring::operator=(const mystring &other) { printf("operator =. \n"); if(&other == this) { return *this; } if(m_data != NULL) { delete [] m_data; }
int len = strlen(other.m_data); m_data = new char[len]; strcpy(m_data, other.m_data);
return *this; }
mystring::~mystring() { printf("destructor.\n"); if(m_data != NULL) { delete [] m_data; } }
#endif
int main() { mystring test1("aaaa"); //normal constructor
printf("=============\n"); mystring test2(test1); //copy constructor
printf("=============\n"); mystring test3; //nornal constructor
printf("=============\n"); test3 = test2; //operator =
printf("=============\n"); mystring test4 = test3; //copy constructor
printf("=============\n"); mystring test5 = "bbb"; //normal constructor
printf("=============\n"); mystring *p = new mystring; //normal constructor
delete p; pause(); }
|
输出结果如下:
normal constructor.
=============
copy constructor.
=============
normal constructor.
=============
operator =.
=============
copy constructor.
=============
normal constructor.
=============
normal constructor.
destructor.
阅读(1189) | 评论(0) | 转发(0) |