温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

当类的成员变量为字符串的时候,注意深拷贝

发布时间:2020-08-06 15:48:03 来源:网络 阅读:349 作者:神ge 栏目:编程语言
#include <iostream>
#include <cstring> #strcpy
using namespace std;

class String{
public:
    String(const char* str = NULL):
        m_str(strcpy(new char[strlen(str?str:"")+1],
        str?str:"")){}
     ~String(){
         if(m_str){
             delete [] m_str;
             m_str = NULL;
         }
     }
     //拷贝构造
     String(const String& that):
         m_str(strcpy(new char[strlen(that.m_str)+1],that.m_str)){}
     //拷贝赋值,成员变量m_str为指针为指针时,要注意深拷贝,这里为深拷贝
     String& operator=(const String& that){
         if(&that != this){
             char* = new char[strlen(that.m_str)+1];
             delete[] m_str;//先释放旧资源
             m_str = strcpy(str,that.m_str);
         }
         return *this;
     }
     friend ostream& operator<<(ostream& os,const String&c){
         os << c.m_str;
         return os;
     }
     //c接口
     const char* c_str(void)const{
         return m_str;
     }
public:
    char* m_str;   
};

int main(void){
    String s1("hello,world");
    cout << s1 << endl;
    return 0;
}
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI