面试

C++面试题-编程

2017-06-20  本文已影响0人  雲凌禹

1、不调用C++/C的字符串库函数,编写strcpy函数

char *strcpy(char *pDest, const char *psrc) {
    assert((pDest != NULL)&&(psrc != NULL));
    char *address = pDest;
    while ( (*pDest++ = *psrc++) != '\0' )
    {
    }
    return address;
}

上述strcpy能够把psrc的内容复制给pdest,为什么还要返回指针地址?
为了实现链式表达式:比如

int length=strlen(strcpy(strDest,“helloworld”));

2、编写类String的普通构造函数、拷贝构造函数、析构函数和赋值函数。

class String{
public:
    String(const char* str = NULL) //普通构造函数 
    {
        if ( NULL == str )
        {
            m_data = new char[1];
            *m_data = '\0';
        }
        else {
            int nLen = strlen(str);
            if (m_data != NULL)
            {
                delete[]m_data;
                m_data = NULL;
            }
            m_data = new char[nLen + 1];
            strcpy(m_data, str);            
        }
    }

    String(const String &other) //拷贝构造函数
    {
        int nLen = strlen(other.m_data);
        m_data = new char[nLen + 1];
        strcpy(m_data, other.m_data);

    }

    ~String() //析构函数
    {
        if ( NULL != m_data )
        {
            delete []m_data;
            m_data = NULL;
        }
    }

    String &operator=(const String &other) //赋值函数
    {
        if (this == &other )
        {
            return *this;
        }
        delete[]m_data;
        int nLen = strlen(other.m_data);
        m_data = new char[nLen + 1];
        strcpy(m_data, other.m_data);
        return *this;
    }

private:
    char *m_data;
};

3、在不使用第三方参数的情况下,交换两个参数i,j的值

void main()
{
       int i = 1;
       int j = 2;
       i = i + j;
       j = i - j;
       i = i - j;
}
上一篇 下一篇

猜你喜欢

热点阅读