日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

String类的构造与析构相关处理

發(fā)布時間:2023/12/1 48 豆豆
生活随笔 收集整理的這篇文章主要介紹了 String类的构造与析构相关处理 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

String類原型:

1 Class String
2 {
3 Public:
4 String(const char *str);
5 String(const String &other);
6 ~String(void);
7 String& operator =(const String &other);
8 Private:
9 char *m_data;
10 };

String的析構函數

1 String::~String(void)
2 {
3 delete []m_data; //由于m_data是內部數據,也可以寫成delete m_data;
4 }

String的構造函數

1 String::String(const char *str)
2 {
3 if(str==NULL)
4 {
5 m_data = new char[1];
6 *m_data = '\0';
7 }
8 else
9 {
10 int length = strlen(str);
11 m_data = new char[length+1];
12 strcpy(m_data, str);
13 }
14 }

String的拷貝構造函數

1 String::String(const String &other)
2 {
3 int length = strlen(other.m_data);
4 m_data = new char[length+1];
5 strcpy(m_data, other.m_data);
6 }

String的拷貝賦值函數

1 String& String::operator =(const String &other)
2 {
3 if(this==&other)
4 return *this;
5 int length = strlen(other.m_data);
6 char *temp = new char[length+1];
7 if(temp!=NULL)
8 {
9 strcpy(temp, other.m_data);
10 delete []m_data;
11 m_data = temp;
12 }
13 return *this;
14 }

?

轉載于:https://www.cnblogs.com/scnutiger/archive/2009/12/13/1622981.html

總結

以上是生活随笔為你收集整理的String类的构造与析构相关处理的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。