String类的编写

#include<iostream>
#include<stdlib.h>
using namespace std;

class String
{

public:

    //当不传值构造时,默认为一个‘\0’

    String() :ptr(new char('\0'))
    {}
    String(const char *x) :ptr(new char[strlen(x) + 1])
    {
        //将x中的字符串拷贝到ptr中
        strcpy(ptr,x);
    }
    String(const String &other)
    {
        //自己拷贝自己情况
        if (this != &other)
        {
            //拷贝构造不可能出现ptr原来就有指向的情况
            ptr = new char[strlen(other.ptr) + 1];
            strcpy(ptr, other.ptr);
        }
    }
    String& operator=(const String &other)
    {
        //自己拷贝自己情况
        if (this != &other)
        {
            //当ptr原来有指向空间时
            if (ptr != NULL)
                delete []ptr;
            ptr = new char[strlen(other.ptr) + 1];
            strcpy(ptr, other.ptr);
        }
        return *this;
    }
    char* GetString()
    {
        return ptr;
    }

    ~String()
    {
        if (ptr != NULL)
            delete[]ptr;
    }
private:
    char *ptr;
};

int main()
{
    char *a = "nihao";
    char *x;
    char *y;
    //构造函数测试
    String test1;
    String test2(a);

    x = test1.GetString();
    y = test2.GetString();

    while (*x != '\0')
        cout << *x++;
    cout << endl;
    while (*y != '\0')
        cout << *y++;
    cout << endl;

    //拷贝构造函数测试
    String test3(test2);
    char *z = test3.GetString();
    while (*z != '\0')
        cout << *z++;
    cout << endl;

    //赋值重载测试
    test1 = test2;
    x = test1.GetString();
    while (*x != '\0')
        cout << *x++;
    cout << endl;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值