c++實現一個簡單的字串類
阿新 • • 發佈:2019-01-22
// string.cpp : 定義控制檯應用程式的入口點。 //c++語言基礎,實現一個簡單的string類 #include <iostream> #include <string> #include "stdlib.h" #include <string.h> using namespace std; class String { public: String(const char *str =NULL);//普通建構函式 String(const String &other ); ~String(); String & operator =(const String &other); String operator +(const String &other);//lianjie bool operator ==(const String &other); //判斷相等 int getLength(); //返回長度 private: char *m_data; }; String::String(const char *str) { if (str == NULL){ m_data = new char[1]; *m_data = '\0'; } else{ int length = strlen(str); m_data = new char[length + 1]; strcpy(m_data, str); } } String::~String() { if (m_data) { delete[] m_data; m_data = 0; } } String::String(const String &other) { if (!other.m_data) //外邊沒資料等於0 { m_data = 0; } m_data = new char[strlen(other.m_data)+1]; strcpy(m_data, other.m_data); } String & String::operator=(const String &other) { if (this != &other) { delete[] m_data; if (!other.m_data) { m_data = 0; } else{ m_data = new char[strlen(other.m_data)+1]; strcpy(m_data,other.m_data); } } return *this; } int String::getLength() { return strlen(m_data); } String String::operator+(const String &other) { //新建一個String物件 String newString; if (!other.m_data) { newString = *this; } else if (!m_data) { newString = other; } else{ newString.m_data = new char[strlen(m_data)+strlen(other.m_data)+1]; strcpy(newString.m_data ,m_data); strcat(newString.m_data,other.m_data); } return newString; } int main( ) { String str1 ="zhaomingming"; int n =str1.getLength(); cout << n <<endl; //若要顯示出來,應該封裝一個show方法。 //printf("%s\n",str1.m_data); String str2 ="jaiojaio"; cout <<str2.getLength()<<endl; String str3(str1); cout <<str3.getLength()<<endl; String str4 = str1+str2; cout <<str4.getLength()<<endl; return 0; }