筆試題(一)
阿新 • • 發佈:2019-02-12
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編譯器環境下,下面的程式的執行結果是:
答案:12 12#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; }
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;