~~~
#include "stdafx.h"
#include <stdlib.h>
#include <string.h>
// delete之后將指針置為NULL防止空指針
#define SAFE_DELETE(p) do{ if(p){delete(p); (p)=NULL;} }while(false);
class String
{
public:
// 普通構造函數
String(const char *str = NULL);
// 拷貝構造函數
String(const String &other);
// 賦值函數(重載操作符=)
String & operator = (const String &other);
// 析構函數
~String();
void printValue(){ printf("%s", m_pcData); };
private:
// 保存字符串的指針
char* m_pcData;
};
String::String(const char *str)
{
if (str == NULL)
{
m_pcData = new char[1];
m_pcData = "\0";
}
else
{
// strlen(str)是計算字符串的長度,不包括字符串末尾的“\0”
size_t len = strlen(str) + 1;
m_pcData = new char[len];
strcpy_s(m_pcData, len, str);
}
}
String::String(const String& other)
{
if (other.m_pcData == NULL)
{
m_pcData = "\0";
}
else
{
int len = strlen(other.m_pcData) + 1;
m_pcData = new char[len];
strcpy_s(m_pcData, len, other.m_pcData);
}
}
String& String::operator = (const String &other)
{
// 如果是自身就直接返回了
if (this == &other)
return *this;
// 判斷對象里面的值是否為空
if (other.m_pcData == NULL)
{
delete m_pcData;
m_pcData = "\0";
return *this;
}
else
{
// 刪除原有數據
delete m_pcData;
int len = strlen(other.m_pcData) + 1;
m_pcData = new char[len];
strcpy_s(m_pcData, len, other.m_pcData);
return *this;
}
}
String::~String()
{
SAFE_DELETE(m_pcData);
printf("\nDestory``````");
}
int main()
{
// 調用普通構造函數
String* str = new String("PWRD");
str->printValue();
delete str;
// 調用賦值函數
String newStr = "CDPWRD";
printf("\n%s\n", newStr);
String copyStr = String(newStr);
copyStr.printValue();
system("pause");
return 0;
}
~~~
調試結果:

- 前言
- C++讀取配置文件
- 結構體內存對齊后所占內存空間大小的計算
- do{}while(0)的妙用
- Cocos2dx實現翻牌效果(CCScaleTo與CCOrbitCamera兩種方式)
- C++的error LNK2019: 無法解析的外部符號編譯錯誤
- Java使用JNI調用C++的完整流程
- strupr與strlwr函數的實現
- strcat函數實現
- Windows上VS使用pthread重溫經典多線程賣票(pthreads-w32-2-8-0-release.exe)(windows上使用pthread.h)
- pthread的pthread_join()函數理解實驗
- 順序存儲結構和鏈式存儲結構的選擇
- C語言冒泡排序
- VS看反匯編、寄存器、內存、堆棧調用來學習程序設計
- 快速排序
- C++的構造函數初始化列表
- fatal error C1083: 無法打開包括文件: “SDKDDKVer.h”: No such file or directory
- C++實現簡單的String類