String类的编写

来源:互联网 发布:怎样进入上层社会 知乎 编辑:程序博客网 时间:2024/06/05 04:17
#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;
}
0 0