From fe1d4056dcb3e72c16d4f4473ae3ea81ac5e3c3c Mon Sep 17 00:00:00 2001 From: BrightHewei <61347887+hewei-nju@users.noreply.github.com> Date: Sat, 19 Feb 2022 02:02:10 +0800 Subject: [PATCH] fix: sizeof(other.m_data) -> strlen(other.m_data) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit sizeof 获取的是指针的字节个数,other.m_data 此时不是数组,是一个指针。 --- back-end.md | 127 +++++++++++++++++++++++++--------------------------- 1 file changed, 62 insertions(+), 65 deletions(-) diff --git a/back-end.md b/back-end.md index 810086c..5134b79 100644 --- a/back-end.md +++ b/back-end.md @@ -499,71 +499,68 @@ Const,volatile修饰指针的含义, 写string类的构造,析构,拷贝函数 String 类的原型如下 - class String - { - public: - String(const char *str=NULL); //构造函数 - String(const String &other); //拷贝构造函数 - ~String(void); //析构函数 - String& operator=(const String &other); //等号操作符重载 - ShowString(); - - private: - char *m_data; //指针 - }; - - String::~String() - { - delete [] m_data; //析构函数,释放地址空间 - } - String::String(const char *str) - { - if (str==NULL)//当初始化串不存在的时候,为m_data申请一个空间存放'\0'; - { - m_data=new char[1]; - *m_data='\0'; - } - else//当初始化串存在的时候,为m_data申请同样大小的空间存放该串; - { - int length=strlen(str); - m_data=new char[length+1]; - strcpy(m_data,str); - } - } - - String::String(const String &other)//拷贝构造函数,功能与构造函数类似。 - { - int length=strlen(other.m_data); - m_data=new [length+1]; - strcpy(m_data,other.m_data); - } - String& String::operator =(const String &other) - { - if (this==&other)//当地址相同时,直接返回; - return *this; - - delete [] m_data;//当地址不相同时,删除原来申请的空间,重新开始构造; - int length=sizeof(other.m_data); - m_data=new [length+1]; - strcpy(m_data,other.m_data); - return *this; - } - - String::ShowString()//由于m_data是私有成员,对象只能通过public成员函数来访问; - { - cout<m_data<m_data << endl; +} + +int main() { + String AD; + char *p = "0123456789"; + String B(p); + AD.ShowString(); + AD = B; + AD.ShowString(); +} +``` 1 指针的四要素