笔试题(一)

1. 以下程序的输出:

#include <iostream> 
   
using namespace std;
  
class Base {
public:
    Base(int j) : i(j) {}
    virtual ~Base() {}

    void func1()
    {
        i *= 10;
        func2();
    } 

    int getValue()
    {
        return i;
    }
 
protected:
    virtual void func2()
    { 
        i++; 
    } 
 
protected: 
    int i;
};
 
class Child : public Base
{
public:
    Child(int j) : Base(j) {}
 
    void func1()
    {
        i *= 100; 
        func2();
    }

protected:
    void func2()
    {
        i += 2;
    }
};
 
int main(void)
{
    Base *pb = new Child(1);
    pb->func1(); 
    cout << pb->getValue() << endl;
    delete pb;
 
    return 0;
}

答案:12

分析:因为 pb 是基类指针,func1非虚函数,所以pb->func1将调用基类中的func1函数。在基类中的func中首先执行 i *= 10,然后执行 func2。但是在调用func2时,因为func2是虚函数,所有这是调用的应该是子类的func2函数,即 i += 2。


2. 下面程序的输出:

#include <iostream>
using namespace std;

#define DOUBLE(x)  x + x // x*2

int main()
{
    int i = DOUBLE(5)*5;
    cout << i << endl;
}

答案:30

分析:int i = 5 + 5 * 5; 


3. 在32位操作系统gcc编译器环境下,下面的程序的运行结果是:

#include <iostream>
using namespace std;

class A
{
public:
    int b;
    char c;
    virtual void print()
    {
        cout << "this is father's function!" << endl;
    }
};

class B : A
{
public:
    virtual void pirnt()
    {
        cout << "this is children's funciton!" << endl;
    }
    virtual void print2()
    {
        cout << "this is children's print2 function!" << endl;
    }
};

int main()
{
    cout << sizeof(A) << "  " << sizeof(B) << endl;
    return 0; 
}
答案:12  12

4. x = x+1, x += 1, x++ 哪个效率最高?为什么?

    x++  >  x += 1  >  x = x + 1

    x = x + 1 :(1)读取右 x 的地址 (2)x + 1 (3)读取左 x 的地址(编译器并不认为左右 x 的地址相同)(4)将右边的值给左边的 x

    x += 1:(1)读取右边 x 的地址 (2)x + 1 (3)将得到的值给 x(因为 x 的地址已经读出)

    x++:(1)读取右 x 的地址 (2)x自增1


5. 取 a,b中较大的值,不用 if,?:,switch语句实现

    int  a, b;

    cin >> a  >> b;

    int  max = (a + b + abs(a - b)) / 2;







  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值