- #include <iostream>
- #include <string>
- using namespace std;
- class string
- {
- private:
- int size;
- char *ptr;
- string() : size(0), ptr(new char[1]) { ptr[0] = 0; }
- string(const string &s) : size(s.size)
- {
- ptr = new char[size + 1];
- strcpy(ptr, s.ptr);
- }
- ~string()
- {
- delete [] ptr;
- }
- friend ostream &operator <<(ostream &, const string &);
- string &operator=(const char *);
- };
- ostream &operator<<(ostream &stream, const string &s)
- {
- return(stream << s.ptr);
- }
- string &string::operator=(const char *chrs)
- {
- if (this != &chrs)
- {
- delete [] ptr;
- size = strlen(chrs);
- ptr = new char[size + 1];
- strcpy(ptr, chrs);
- }
- return(*this);
- }
- int main()
- {
- string str;
- str = "Hello World";
- cout << str << endl;
- return(0);
- }
- /string></iostream>
来源: https://mp.weixin.qq.com/s?__biz=MzU4ODM1MTQyOA==&mid=2247483785&idx=1&sn=441a4a1f20bbed85b343f741c713a48c&chksm=fddf5322caa8da3410323f4a1d6b28512829e2b4468ab46e365ebc37d890d6e45782e736330b#rd