string类构造函数、拷贝构造函数、赋值函数、析构函数

来源:互联网 发布:php memcache redis 编辑:程序博客网 时间:2024/06/11 16:43
#ifndef DDSTRING_H#define DDSTRING_Hclass ddString {public:    ddString(const char *pStrAddr = 0);    ddString(const ddString &otherStr);    ddString &operator=(const ddString &otherStr);    unsigned int size() const;    char *getData() const;    ~ddString();private:    char *pddStr;};#endif

#include <string.h>#include "ddString.h"ddString::ddString(const char *pStrAddr){    if (pStrAddr) {        unsigned int size = strlen(pStrAddr);        pddStr = new char[size+1];        strcpy(pddStr, pStrAddr);    } else {        pddStr = new char[1];        *pddStr = '\0';    }}ddString::ddString(const ddString &otherStr){    unsigned int size = otherStr.size();    pddStr = new char[size+1];    strcpy(pddStr, otherStr.pddStr);}ddString &ddString::operator=(const ddString &otherStr){    //if they have same pointers, they are same    if (this != &otherStr) {        //delete old resource        delete[] pddStr;        unsigned int size = otherStr.size();        pddStr = new char[size+1];        strcpy(pddStr, otherStr.pddStr);    }    return(*this);}unsigned int ddString::size() const{    return(strlen(pddStr));}char *ddString::getData() const{    return(pddStr);}ddString::~ddString(){    if (pddStr != 0) {        delete[] pddStr;        pddStr = 0;    }}


0 0