加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c++ 可变长的String类

发布时间:2020-12-16 10:47:28 所属栏目:百科 来源:网络整理
导读:#include iostream #include cstring using namespace std; class String{ private : char * str; public : String():str(NULL){}; const char * getStr() const // 此处注意要设置为常量成员函数,防止str所指向的内容被修改。 { return str; } String oper
#include <iostream> 
#include <cstring>
using namespace std;

class String
{
private:
    char *str;
public:
    String():str(NULL){};
    const char * getStr() const//此处注意要设置为常量成员函数,防止str所指向的内容被修改。 
    {
        return str;
    }
    String & operator=(const String &);//赋值运算符实现深复制 
    String(const String&);    //复制构造函数实现深复制 

    String & operator=(const char *);
    ~String();

} ;

String & String::operator=(const String & s)
{
    if(s.str==str)//防止不经意间出现自己复制自己时的bug 
        return *this;
    if(str)
    {
        delete []str;
        str=new char[strlen(s.str)+1];
        strcpy(str,s.str);
    }
    else
        str=NULL;
    return *this;
}
String::String(const String & s)
{
    str=new char(strlen(s.str)+1);
    strcpy(str,s.str);
}

String & String::operator=(const char * s)
{
    if(str)
        delete []str;
    if(s)
    {
        str=new char[strlen(s)+1];
        strcpy(str,s);
    }
    else
    {
        str=NULL;
    }
    return *this;
}
String::~String()
{
    if(str)
        delete [] str;
}

int main()
{
    
        String s,s1;
        s="xxx";
        cout<<s.getStr()<<endl;
        s="ssss";
        cout<<s.getStr()<<endl;

        s=s;
        s1="ddddd";
        s=s1;

    


    return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读