那么多C++试题,其实最关键的是要知道考察的知识点在哪里。哎,应该好好重新看看《effective c++》了。
网易3道C++试题:
题目1:
- class A
- {
- public:
- A(int j):i(j)
- {
- fun1(); //here:在构造函数中调用了虚函数
- }
- ~A()
- {
- }
- void fun1()
- {
- i *= 10;
- fun2();
- }
- int getValue(){
- return i;
- }
- protected:
- virtual void fun2()
- {
- i++;
- }
- private:
- int i;
- };
- class B:public A
- {
- public:
- B(int j):A(j)
- {
- }
- virtual ~B()
- {
- }
- void fun1()
- {
- i *= 100;
- fun2();
- }
- protected:
- void fun2()
- {
- i += 2;
- }
- private:
- int i;
- };
- int main()
- {
- A* p = new B(1);
- cout<<p->getValue()<<endl;
- delete p;
- return 0;
- };
考点:在构造函数中调用了虚函数。
根据《effective c++》条款09:绝不要在构造函数和析构函数中调用虚函数,因为:这类调用从不下降至子类。此时,对象在derived class调用之前,绝不会成为一个derived对象。
所以,答案是11(而不是12)。
题目2:
- class A{
- public:
- virtual int fun(int i = 1);
- };
- int A::fun(int i){return i + 1;}
- class B:public A{
- public:
- virtual int fun(int i = 10);
- };
- int B::fun(int i){return i;}
- int main()
- {
- // A* p = new B(1);
- // cout<<p->getValue()<<endl;
- // delete p;
- A *p = new B();
- cout << p->fun();
- return 0;
- };
考点:哎,虚函数是动态绑定的,但是默认参数是静态绑定的。
所以,答案是1。而不是10。靠!
题目三:
考察C++中static 成员、const成员、static const成员的初始化时机:
在C++中,static静态成员变量不能在类的内部初始化。在类的内部只是声明,定义必须在类定义体的外部,通常在类的实现文件中初始化,如:double Account::Rate=2.25;static关键字只能用于类定义体内部的声明中,定义时不能标示为static
在C++中,const成员变量也不能在类定义处初始化,只能通过构造函数初始化列表进行,并且必须有构造函数。
const数据成员 只在某个对象生存期内是常量,而对于整个类而言却是可变的。因为类可以创建多个对象,不同的对象其const数据成员的值可以不同。所以不能在类的声明中初始化const数据成员,因为类的对象没被创建时,编译器不知道const数据成员的值是什么。
const数据成员的初始化只能在类的构造函数的初始化列表中进行。要想建立在整个类中都恒定的常量,应该用类中的枚举常量来实现,或者static cosnt。
一个例子如下:
- class Test
- {
- public:
- Test():a(0){}
- enum {size1=100,size2=200};
- private:
- const int a;//只能在构造函数初始化列表中初始化
- static int b;//在类的实现文件中定义并初始化
- const static int c;//与 static const int c;相同。
- };
- int Test::b=0;//static成员变量不能在构造函数初始化列表中初始化,因为它不属于某个对象。
- cosnt int Test::c=0;//注意:给静态成员变量赋值时,不需要加static修饰符。但要加cosnt
腾讯笔试题目:
- #include <iostream>
- using namespace std;
- class A
- {
- public:
- int m_a;
- A():m_a(1){}
- virtual void f(){}
- };
- class B:public A
- {
- public:
- int m_a;
- B():m_a(2){}
- virtual void f(){}
- };
- int main()
- {
- A *a=new B();
- B *b=dynamic_cast<B*>(a);
- cout<<b->m_a<<endl;
- return 0;
- }
主要是引申dynamic_cast 和static_cast的区别,自己看看百科吧:
http://baike.baidu.com/view/1745213.htm。
dynamic_cast的类一定要加virtual函数。
FROM: http://blog.csdn.net/randyjiawenjie/article/details/6871660