1.-个C++类- 般至少有四大函数,即构造函数、拷贝构造函数、析构函数和赋值函数。 设计并实现自己的字符串类(不要直接包含string.h)

1.-个C++类- 般至少有四大函数,即构造函数、拷贝构造函数、析构函数和赋值函数。

设计并实现自己的字符串类(不要直接包含string.h)

class MyString

{ char* value;

//constructor

// copy constructor

//destructor

//getLength()返回有效字符个数//concat(MyString&)合并两个字符串

//getChar(int);返回某个位置的字符//replaceChar(char )替换成新字符};

所需参数返回值及其他数据、函数自行设计。#c++

赋值是要重载=操作符,还是set/get?

#include <iostream>
using namesapce;
class MyString
{ 
    char* value;
public:
    MyString() {value = NULL;}
    MyString(char *v)
    {
        if(v != NULL)
        {
            int i=0;
            while(v[i++] != '\0');
            value = new char[i];
            i=0;
            while(v[i] != '\0')
            {
                value[i] = v[i];
                i++;
            }
            value[i] = '\0';
        }
    }
    MyString(MyString &s) 
    {
        int len = s.getLength();
        value = new char[len+1];
        int i=0;
        while(s.value[i] != '\0')
        {
            value[i] = s.value[i];
            i++;
        }
        value[i] = '\0';
    }
    ~MyString() {if(value != NULL) delete value;}
    const int getLength() 
    {
        if(value == NULL)
            return 0;
        int i=0;
        while(value[i++] != '\0');
        return i-1;
    }
    char getChar(int idx)
    {
        return value[idx];
    }
    void replaceChar(int idx,char newChar)
    {
        value[idx] = newChar;
    }
    void concat(MyString &s)
    {
        int len = getLength();
        char *v = new char[s.getLength() + len + 1];
        int i;
        for(i=0;i<len;i++)
            v[i] = value[i];
        for(i=0;i<s.getLength();i++)
            v[len+i] = s.value[i];
        v[len+i] = '\0';
        if(value != NULL)
            delete value;
        value = v;
    }
    MyString& operator = (MyString &s)
    {
        if(value != NULL)
            delete value;
        int len = s.getLength();
        value = new char[len + 1];
        int i;
        for(i=0;i<len;i++)
            value[len+i] = s.value[i];
        value[len+i] = '\0';
        return *this;
    }
    void print() {if(value != NULL) cout<<value<<endl;}
};

int main()
{
    MyString s1("Hello");
    MyString s2(" World");
    MyString s3(s1);
    s1.print();
    s3.print();
    s1.concat(s2);
    s1.print();
    s1.replaceChar(3,'G');
    s1.print();
    return 0;
}