C++编写一个字符串类 MyString, 其中用字符数组来存储字符串

类声明形式如下:

class MyString
{
      char  str[100];         //存储字符串的数据成员
   public:
      MyString() {      };      //默认构造函数(已完成)
MyString(char a[]);    //带参数构造函数,通过形参a把一个字符串初始化到str中
MyString(MyString &p);  //复制构造函数
void Disp();                 //打印字符串  
      int length();                 //计算数组str中字符串的实际长度;
      void mystrcat(char a[]);    //把形参a中的字符串连接到str中字符串的后面(这里不要直接使用strcat函数)
};

试按注释说明给出所列成员函数在类外的实现过程, 并在主函数中进行验证。


#include <iostream>
using namespace std;

class MyString
{
        char  str[100];         //存储字符串的数据成员
    public:
        MyString(){str[0] = 0;};      //默认构造函数(已完成)
        MyString(char a[]);    //带参数构造函数,通过形参a把一个字符串初始化到str中
        MyString(MyString &p);  //复制构造函数
        void Disp();                 //打印字符串
        int length();                 //计算数组str中字符串的实际长度;
        void mystrcat(char a[]);    //把形参a中的字符串连接到str中字符串的后面(这里不要直接使用strcat函数)
};

MyString::MyString(char a[])
{
    int i = 0;

    while(str[i] = a[i]) ++i;
}

MyString::MyString(MyString &p)
{
    new(this)MyString(p.str);
}

int MyString::length()
{
    int i = 0;
    while(str[i])++i;

    return i;
}

void MyString::Disp()
{
    cout << str << endl;
}

void MyString::mystrcat(char a[])
{
    int len = length();
    int i = 0;

    while(str[len++] = a[i++]);
}

int main()
{
    MyString s1;
    s1.Disp();
    cout << s1.length() << endl;

    MyString s2("123456");
    s2.Disp();
    cout << s2.length() << endl;

    MyString s3(s2);
    s3.Disp();
    cout << s3.length() << endl;

    s3.mystrcat("abcd");
    s3.Disp();
    cout << s3.length() << endl;

    return 0;
}