C++面试题-编程

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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1 文件结构 每个C++/C程序通常分为两个文件。一个文件用于保存程序的声明(declaration),称为头文件...
    Mr希灵阅读 2,899评论 0 13
  • 题目类型 a.C++与C差异(1-18) 1.C和C++中struct有什么区别? C没有Protection行为...
    阿面a阅读 7,727评论 0 10
  • 前言 把《C++ Primer》[https://book.douban.com/subject/25708312...
    尤汐Yogy阅读 9,544评论 1 51
  • 一、 C/C++程序基础 面试例题1——分析代码写输出(一般赋值语句的概念和方法)。 面试例题2—...
    LuckTime阅读 2,041评论 2 42
  • 1.在C++ 程序中调用被C 编译器编译后的函数,为什么要加extern “C”? 答:首先,extern是C/C...
    曾令伟阅读 927评论 0 4