Chinaunix首页 | 论坛 | 博客
  • 博客访问: 207214
  • 博文数量: 38
  • 博客积分: 2060
  • 博客等级: 大尉
  • 技术积分: 388
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-17 10:10
文章分类

全部博文(38)

文章存档

2011年(1)

2009年(37)

我的朋友

分类: C/C++

2009-08-12 15:15:36

一个string类,笔试中常遇到的:
 

/****************************************
 *
 *
 *
 * ***************************************/


#ifndef __MYSTRING_H__
#define __MYSTRING_H__

#include <unistd.h>
#include <string.h>
#include <stdio.h>

class mystring
{
    private:
        char *m_data;
    protected:
    public:
        mystring(const char *p = NULL);
        mystring(const mystring &other);
        ~mystring(void);
        mystring &operator=(const mystring &other);
};

mystring::mystring(const char *p)
{
    printf("normal constructor.\n");
    if(p == NULL)
    {
        m_data = new char[1];
        m_data[0] = '\0';
    }
    else
    {
        int len = strlen(p);
        m_data = new char[len+1];
        strcpy(m_data, p);
    }
}

mystring::mystring(const mystring &other)
{
    printf("copy constructor.\n");
    int len = strlen(other.m_data);
    m_data = new char[len];
    strcpy(m_data, other.m_data);
}

mystring &mystring::operator=(const mystring &other)
{
    printf("operator =. \n");
    if(&other == this)
    {
        return *this;
    }
    if(m_data != NULL)
    {
        delete [] m_data;
    }

    int len = strlen(other.m_data);
    m_data = new char[len];
    strcpy(m_data, other.m_data);

    return *this;
}

mystring::~mystring()
{
    printf("destructor.\n");
    if(m_data != NULL)
    {
        delete [] m_data;
    }
}

#endif

int main()
{
    mystring test1("aaaa");    //normal constructor

    printf("=============\n");
    mystring test2(test1);    //copy constructor

    printf("=============\n");
    mystring test3;    //nornal constructor

    printf("=============\n");
    test3 = test2;    //operator =

    printf("=============\n");
    mystring test4 = test3;    //copy constructor

    printf("=============\n");
    mystring test5 = "bbb";    //normal constructor

    printf("=============\n");
    mystring *p = new mystring; //normal constructor

    delete p;
    pause();
}

 

输出结果如下:

normal constructor.
=============
copy constructor.
=============
normal constructor.
=============
operator =.
=============
copy constructor.
=============
normal constructor.
=============
normal constructor.
destructor.

 

阅读(1044) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~