您的位置:首页 > 其它

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

2014-02-05 20:52 274 查看
#ifndef DDSTRING_H
#define DDSTRING_H

class 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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐