首页 > 编程语言 >C++面对对象:实现string类

C++面对对象:实现string类

时间:2023-02-22 02:11:06浏览次数:38  
标签:const String strlen C++ char str data 面对 string

 1 //string.h
 2 #pragma once
 3 class String {
 4 public:
 5     String(const char* cstr = 0);
 6     String(const String& str);
 7     ~String();
 8     
 9     String& operator = (const String& str);
10     String& operator += (const String& str);
11     
12     char* get_c_str() const { return m_data; }
13 private:
14     char* m_data;
15 };
16 
17 #include <cstring>
18 inline String::String(const char* cstr) {
19     if (cstr) {
20         m_data = new char[strlen(cstr) + 1];
21         strcpy(m_data, cstr);
22     }
23     else {
24         m_data = new char[1];
25         *m_data = '\0';
26     }
27 }
28 
29 inline String::String(const String& str) {
30     m_data = new char[strlen(str.m_data) + 1];
31     strcpy(m_data, str.m_data);
32 }
33 
34 inline String::~String() {
35     delete[] m_data;
36 }
37 
38 inline String& String::operator = (const String& str) {
39     if (this == &str) {
40         return *this;
41     }
42     delete[] m_data;
43     m_data = new char[strlen(str.m_data) + 1];
44     strcpy(m_data, str.m_data);
45     return *this;
46 }
47 
48 inline String& String::operator += (const String& str) {
49     char* p = m_data;
50     m_data = new char[strlen(str.m_data) + strlen(m_data) + 1];
51     strcpy(m_data, p);
52     strcpy(m_data + strlen(m_data), str.m_data);
53     delete[] p;
54     return *this;
55 }
 1 //string.cpp
 2 #include <iostream>
 3 #include "string.h"
 4 using namespace std;
 5 
 6 ostream& operator << (ostream& os, const String& str) {
 7     return os << str.get_c_str();
 8 }
 9 
10 int main()
11 {
12     String s1("hello");
13     String s2("world!!!");
14     
15     String s3(s2);
16     cout << s1 << " " << s2 << " " << s3 << endl;
17 
18     s3 = s1;
19     cout << s1 << " " << s2 << " " << s3 << endl;
20 
21     s3 += s2;
22     cout << s3 << endl;
23 
24     String s4;
25     String s5(s4);
26     cout << s4 << " " << s5 << endl;
27     s5 += s2;
28     cout << s4 << " " << s5 << endl;
29     return 0;
30 }

 

标签:const,String,strlen,C++,char,str,data,面对,string
From: https://www.cnblogs.com/karinto/p/17143056.html

相关文章