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;