腾讯2013实习生招聘笔试题目(1)

1、下面错误的有:
int i; 
char a[10]; 
string f();  
string g(string &str);   

A. if(!!i){f();}  B. g(f());  C. a=a+1;  D. g("abc");

A和C比较容易判断:A真确,C错误。

对于B和D,情况要复杂一些: (MyString为自定义string)

(1) 函数参数为非MyString引用的情况

void g(const MyString str)  // 或者没有const
{
}

int main(void)
{
    MyString a;
    g(a);
    cout << "end" << endl;
    return 0;
} 输出: MyString()
// 生成a的时候输出 copy constructor // 生成str的时候输出 ~MyString() // g函数执行完毕时,str析构时输出 end ~MyString() // a析构时输出

--------------------------------------------------
int main(void)
{
g("abc");
return 0;
}
输出:

MyString(const char *pData)

 ~MyString()

 
2、函数参数为MyString的引用的时候

void g(MyString &str)
{
}

int main(void)
{    
    MyString a;
    g(a);

    cout << "end" << endl;
}

输出:
MyString()
end
~MyString()
----------------------------------
int main(void)
{
g("abc");
// 此处出现编译错误。为了便于解释,作以下处理
// const MyString temp("abc");
// g(temp);
// 实参是const对象,但是形参却是非常量引用,所以报错
// 如果函数g改为 void g(const MyString &str),则g("abc")是正确的
return 0;
}

 

3、函数的返回值为基本数据类型和类对象的时候

#include<iostream>
using namespace std;

class A
{};

A getA()
{
    A a;
    return a;
}

int getInt()
{
    return 6;
}

int main(void)
{
    A x;
    getA() = x;    //ok,临时的对象可寻址
    getInt() = 6;  //error,临时的基本数据类型不可寻址

    return 0;
}
4、函数g和f结合起来
MyString f()
{
    MyString a("hello");
    return a;
}

void g(MyString &str)
{
}

int main(void)
{
        g(f());
        // 可以理解为 函数f返回时通过拷贝构造函数生成了MyString类的一个对象temp,
        // g(temp); 如果函数f变为 const MyString f(),则g(f())明显是错误的。
        retrun 0;
}

输出:
MyString(const char *pData)
copy constructor
~MyString()
~MyString()

 

posted on 2013-09-20 12:39  江在路上2  阅读(271)  评论(0编辑  收藏  举报