Multiple-choice questions.(單選題)
1.1. (5%) Consider the following C++ code.
#include <iostream>
using namespace std;
class Copied {
public:
int* num;
int len;
Copied (int length) {
num = new int[100];
for (int i = 0; i < 100; i++) num[i] = i;
len = 100;
}
Copied (const Copied& c) : // Line A
num(c.num), len(c.len) { }
virtual Copied operator=(const Copied& c) {return Copied(c);}
};
int main( ) {
Copied n1(5);
Copied n2(n1);
n2.num[0] = 50;
cout << "n2.num[0] = " << n2.num[0];
cout << ", n1.num[0] = " << n1.num[0];
cout << endl;
}
What is printed by the cout statements in main? (a) n2.num[0] =50, n1.num[0] = 50 (b) n2.num[0] = 50, n1.num[0] = 0 (c) n2.num[0] = 0, n1.num[0] = 50 (d) n2.num[0] = 0, n1.num[0] = 0 (e) There is an error because << is not overloaded by the copied class.
1.2. (5%) Continue the problem 1.3. Replace the constructor Copied (const Copied& c) at (Line A) above with the code below. With this new constructor, what is printed by the cout statement?
Copied (const Copied& c) : len(c.len) {
num = new int[len];
for (int i = 0; i < len; i++) { num[i] = c.num[i]; }
}
(a) n2.num[0] = 50, n1.num[0] = 50 (b) n2.num[0] = 50, n1.num[0] = 0 (c) n2.num[0] = 0, n1.num[0] = 50 (d) n2.num[0] = 0, n1.num[0] = 0 (e) n2.num[0] = 50, n1.num[0] = 50 (f) There is an error because << is not overloaded by the copied class.
1.3. (5%) A function prototype does not have to ______. (a) include argument names (b) end with a semi-colon (c) agree with the function header (d) match with all calls of the function
1.4. (5%) In C++, to exhibit polymorphism it is necessary to ______. (a) declare all methods that will exhibit polymorphic behavior as virtual (b) access the methods by a pointer or reference (c) declare the class as abstract (d) declare the class as polymorphic (e) (a) and (b) (f) (a) and (c) (g) (a) and (e)
1.1 Line A 的 copy constructor 只複製指標 num(c.num),是 shallow copy;n2.num 與 n1.num 指向同一塊陣列,n2.num[0]=50 也改到 n1.num[0] → 兩個都印 50 → (a)
1.2 新 copy constructor 先 new int[len] 再逐一複製,是 deep copy;n2 有自己的陣列,改 n2.num[0] 不影響 n1,n1.num[0] 仍是建構時的 0 → (b)
cout 印的是 int,不需要為 Copied 重載 <<;1.2 的 (a)(e) 內容相同,是共用陣列時的結果
1.3 prototype 只需要參數型別,名稱可省(int f(int, double););它是宣告,必須以分號結尾;必須和 function header 一致,每次呼叫也要和它相容 → (a)
1.4 要 dynamic binding:(a) 方法要宣告成 virtual;(b) 要經由 base class 的 pointer 或 reference 呼叫(直接用物件呼叫在編譯期就綁定了);不一定要 abstract class,C++ 也沒有「宣告 class 為 polymorphic」的語法 → (a) 且 (b) = (e)
1.1 (a) 1.2 (b) 1.3 (a) 1.4 (e)