您的位置:首页 > 编程语言 > C语言/C++

常见C++笔试题目整理(含答案)6

2010-02-28 22:28 603 查看
网上流传的一份常见C++笔试题目汇总,供各位有找工作需要的同学参考之用,因为原文较长,遂采用连载形式,预计需要连载10期左右,有耐心的同学就请一直跟下去吧,相信一定会有所收获。

提前说明一点,题目来在网络,答案是网上资料配的仅供参考,已经有许多大侠发现了其中的问题,如有同学觉得哪道题目有异议,欢迎讨论!

题目41-45

41. 分析一下这段程序的输出 (Autodesk)
class B
{
public:
B()
{
cout<<"default constructor"<<endl;
}
~B()
{
cout<<"destructed"<<endl;
}
B(int i):data(i) //B(int) works as a converter ( int -> instance of B)
{
cout<<"constructed by parameter " << data <<endl;
}
private:
int data;
};
B Play( B b)
{
return b ;
}

(1) results:
int main(int argc, char* argv[]) constructed by parameter 5
{ destructed B(5)形参析构
B t1 = Play(5); B t2 = Play(t1);   destructed t1形参析构
return 0;               destructed t2 注意顺序!
} destructed t1
(2) results:
int main(int argc, char* argv[]) constructed by parameter 5
{ destructed B(5)形参析构
B t1 = Play(5); B t2 = Play(10);   constructed by parameter 10
return 0;               destructed B(10)形参析构
} destructed t2 注意顺序!
42. 写一个函数找出一个整数数组中,第二大的数 (microsoft)
答案:
const int MINNUMBER = -32767 ;
int find_sec_max( int data[] , int count)
{
int maxnumber = data[0] ;
int sec_max = MINNUMBER ;
for ( int i = 1 ; i < count ; i++)
{
if ( data > maxnumber )
{
sec_max = maxnumber ;
maxnumber = data ;
}
else
{
if ( data > sec_max )
sec_max = data ;
}
}
return sec_max ;
}
43. 写一个在一个字符串(n)中寻找一个子串(m)第一个位置的函数。
KMP算法效率最好,时间复杂度是O(n+m)。
44. 多重继承的内存分配问题:
比如有class A : public class B, public class C {}
那么A的内存结构大致是怎么样的?

这个是compiler-dependent的, 不同的实现其细节可能不同。
如果不考虑有虚函数、虚继承的话就相当简单;否则的话,相当复杂。
可以参考《深入探索C++对象模型》,或者:
http://blog.csdn.net/wfwd/archive/2006/05/30/763797.aspx
45. 如何判断一个单链表是有环的?(注意不能用标志位,最多只能用两个额外指针)

struct node { char val; node* next;}

bool check(const node* head) {} //return false : 无环;true: 有环
一种O(n)的办法就是(搞两个指针,一个每次递增一步,一个每次递增两步,如果有环的话两者必然重合,反之亦然):
bool check(const node* head)
{
if(head==NULL) return false;
node *low=head, *fast=head->next;
while(fast!=NULL && fast->next!=NULL)
{
low=low->next;
fast=fast->next->next;
if(low==fast) return true;
}
return false;
}



未完,待续,进入“我的笔记”看连载的系列的下一回!

如果你想同我交流,欢迎点击链接http://student.csdn.net/invite.php?u=113322&c=a139a65a1494291d和我成为好友!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: