C++实现String类

    xiaoxiao2021-03-25  118

    C++实现String类

    @(C++代码)[C++实现, 学习笔记]

    String.h

    #ifndef String_h #define String_h #include <iostream> #include <cstring> using namespace std; //类的构建 class String { friend ostream& operator<<(ostream& out,String& s); friend istream& operator>>(istream& in ,String& s); public: String(const char* c=NULL); String(const String &s); String operator+(const String &s); String operator=(const String &s); bool operator==(const String &s); char operator[](int index); ~String(void){delete[] str;} size_t size(){return strlen(str);} //private: char* str; }; //功能的实现 inline String::String(const char* c) { if(!c) { str = NULL; } else { str = new char[strlen(c)+1]; strcpy(str,c); } } inline String::String(const String &s) { if(!s.str) { str = NULL; } else { str = new char[strlen(s.str)+1]; strcpy(str,s.str); } } inline String String::operator=(const String &s) { if(this!=&s) { delete[] str; if(!s.str) { str = NULL; } else { str = new char[strlen(s.str)+1]; strcpy(str,s.str); } } return *this; } inline String String::operator+(const String &s) { String newStr; if(!s.str) { newStr = *this; } else if(!str) { newStr = s; } else { newStr.str = new char[ strlen(str) + strlen(s.str) + 1]; strcpy(newStr.str , str); strcat(newStr.str , s.str); } return newStr; } inline bool String::operator==(const String &s) { if(strlen(str) != strlen(s.str)) return false; if(strcmp(str,s.str)==0) return true; else return false; } inline char String::operator[](int index) { return str[index]; } ostream& operator<<(ostream& out, String &s) { out << s.str; return out; } istream& operator>>(istream& in , String& s) { char tmp[255]; s = ""; do { in.get(tmp, 255); s = s + tmp; }while(tmp[0]!=0); return in; } #endif /* String_h */
    转载请注明原文地址: https://ju.6miu.com/read-6585.html

    最新回复(0)