# CH15
*6-9晨,10-14誼,15-19安,20-24婕,25-28吉*
*可以標一下答案是從簡報第幾頁或是gpt來的!!*
**1. What are the two additional programming paradigms that C++ can provide?**(p.4)
object-oriented programming物件導向
generic programming泛型設計
**2.What functionality can C++ provide for object-oriented programming? Give five examples.**(p.4)
classes, encapsulation, objects, operator overloading, inheritance and polymorphism
**3. Give a C++ program to input two integers from keyboard and output their product to monitor. Any C-style statement is prohibited.**
```cpp==
#include <iostream>
int main()
{
std::cout << "Enter first integer";
int number1;
std::cin >> number1;
std::cout << "Enter second integer";
int number2;
std::cin >> number2;
int product = number1 * number2;
std::cout << "Product is" << product << std::endl;
}
```
**4. Give an inline function to find the maximum of three integers.**
```cpp=
inline int max(int a, int b, int c)
{
if(a >= b && a >= c){
return a;
}else if(b >= a && b >= c){
return b;
}else{
return c;
}
}
```
**5. Why we can't simply use cout/cin but use std::cin, std::cout? What statement should be used if we want to omit the std:: prefix?**
1. `std::cin`和`std::cout`表示`cout`和`cin`屬於命名空間`std`
2.
```cpp=
using namespace std;
```
**6. Where should we place the definition of `inline` functions so that they can be reused? Why?**(p.31)
placed in header files.
定義可以包含在來源檔案中。這樣header file的定義可以包含在每個引用header file的程式中
**7. Distinguish pass-by-value and pass-by-reference in C++.**(p.36, 37)
pass-by-value:a copy of the argument’s value is made and passed傳遞的值是複製後的,不會影響本來的值
pass-by-reference:ability to access the caller’s data直接存取本來的參數
**8. Give two function definitions of calculating box volume (length, width, height) using pass-by-value and pass-by-reference.**
```cpp=
double calculateVolumeByValue(double length, double width, double height) {
return length * width * height;
}
```
```cpp=
void calculateVolumeByReference(double length, double width, double height, double &result) {
result = length * width * height;
}
```
**9. How to pass a large object efficiently and safely?**(chatgpt)
使用reference或是pointer
**10. Given the following code:**
```cpp
double x = 2.0;//x被初始化為 2.0
double &y = x;//y和x指向同一個記憶體位置
double *z = &y;//z是指向y地址的指標。因為y是x的參考,所以z實際上指向x
x = y * (*z);//x = 2 * 2
y++;//x = 4 + 1 = 5 = y
(*z) -= 2;// z = x = 5 - 2 = 3 = y
```
**What are the values of x, y, and z?**
x = 3, y = 3, z = 3
**11. What will occur if a reference variable was not initialized? Explain.**(p46)
編譯錯誤。因為引用變數在宣告時必須初始化,並且引用必須指向一個具體的變數,無法留作未初始化狀態。
**12. When can we pass constant or expression returning an `rvalue`to a function using pass-by-reference?**(p46)
當函數參數是 rvalue (使用 && 聲明)時
**13. What would occur for the following function prototype? Explain.**
```cpp
void mystery(int &x = 1, double &y = 2);
```
編譯錯誤,不能有初設值
```cpp
void mystery(int &x, double &y);
```
> [name=vina chang]參考變量通常只向左值,而非右值
**14. What is the problem of returning a reference of a automatic variable?**(返回自動變量的參考會產生什麼問題?)(p48)
變量在函數結束時被丟棄,造成dangling reference,導致程式行為不可預測
**15. Distinguish the difference between C and C++ in the following function prototype:void print();**
C語言中pritnf()就是一個函數且可以接受任意數量的參數,因為是void所以沒有回傳值;C++中printf()是依函數不接受任何參數而且沒有回傳值。(p.49)
- 在C中,空的傳入值`print()`表示不檢查參數,意思是可以傳遞任何參數給這個function
- 在C++中,空的傳入值`print()`表示這個function沒有傳入值,如果傳入任何參數都會報錯
**16. Where should we put function's default arguments?**
Default arguments must be the rightmost (trailing) arguments in a function’s parameter list.(p.51)
**17. Give a function to calculate the offset of an object with uniform accelerated motion, where the velocity and acceleration has default values 10 and 9.8, respectively.**
```cpp=
#include <iostream>
double calculateOffset(double t, double v0 = 10.0, double a = 9.8) {
return v0 * t + 0.5 * a * t * t;
}
int main() {
double time ;
cin >> time;
double offset = calculateOffset(time);
std::cout << offset << std::endl;
double customOffset = calculateOffset(time, 15.0, 8.0);
std::cout << customOffset << std::endl;
return 0;
}
```
**18. Given global variable `x` and a local variable with the same name. How to explicitly access the global one?**
用::(p.57)
**19. Briefly describe function overloading in C++.**
定義多個具有相同名稱但參數列表中含不同數量或類型的函數且編譯器會根據提供的參數列表決定使用哪個函數。(p.61)
**20. How the compiler differentiates overloaded functions?**

**21. What problem will occur for the following code:**
```cpp
int mystery(int x);
char mystery(int x);
```
**Explain your answer.**

**22. When should we use function template rather than overloaded functions?**

**23. Give a function template for calculating the product of three values of any type.**

**24. How to initialize an array of ten integers using the standard class template vector? How to input the ten integer from keyboard by a function using pass-by-reference?**

**25. Answer the following questions about vector.**
**a) How to declare a vector of type float?**
```cpp=
vector <float> vec; // p.84
```
**b) How to determine the size of a vector?**
```cpp=
vector <float> vec(5); // p.84
```
**c) Give two ways to access an element of a vector.**
```cpp=
vec[3]; // line 66
vec.at(3) // line 78
// p.94 解釋
// p.85 程式碼
```
**26. How to catch the exception when accessing a vector with out-of-range subscript?**
```cpp=74
// use try-catch block p.85 & p.99
try
{
cout << vec.at(15) << endl;
}
catch( out_of_range &ex )
{
cout << ex.what() << endl;
}
```
**27. What are the two kinds of components in a class?** (p.112)
`data members` 和 `member functions`
> `data member` 表示 `class` 裡面的資料和變數
> `member functions` 是表示 `class` 裡面的副程式
**28. How can object-oriented design perform information hiding?**(p.109) & Chat GPT-4o
因為C++是一個物件導向設計的程式語言,使用「封裝」的方法來限制外部對物件的某些組件進行直接訪問
# CH16
*9誼,11安,12晨,13吉*
**1. How to perform data hiding when constructing a user-defined class?**
Declaring data members with access specifier `private`
**2. Who can access the private data members of a given class?**(p.26)
member function
**3. Explain the functionality of mutators and accessors in a class.**(p.30)
mutators:mutate, or change, values(改變值)
accessors: access values(存取值)
**4. Briefly describe the role of constructors in classes.**(p.32)
初始化物件
initialize an object of the class when the object is created
**5. What will occur when an object is instantiated(實例化)? What is the main advantage of such mechanism(機制)?**
分配記憶體並初始化資料成員。
封裝性和程式碼組織性高。
* 假設建立一個名為`Car`的類別時,可在類別中定義各種屬性,比如`brand`、`model`和`year`。這些屬性可以被設置為private,這樣它們就只能在`Car`類別的內部被訪問。當創建一個`Car`物件時,你可能會使用一個名為`ToyotaCorolla`的實例,可以設置`brand`為"Toyota"、`model`為"Corolla"、`year`為2022。這樣做的好處在於,即使外部程式碼無法直接訪問這些屬性,但可以使用`Car`類別中的方法來設置和獲取這些屬性,這樣可以確保資料的安全性並提供更好的封裝。
**6. How to use member initializer list to initialize data members? Give a simple example.**
```cpp=!
#include <iostream>
using namespace std;
class Name
{
private:
string name; // private data member
public:
Name(string inp) : name(inp) // constructor
{
}
string getName() { // member function
return name;
}
};
int main()
{
Name student("John");
cout << student.getName() << endl;
}
```
**7. Give the definition of a default constructor. How can a class get its default constructor?p39**
任何不帶參數的constructor。
如果該類別沒有任何使用者定義的constructors,編譯器將implicitly創建一個default constructor。
**8. What is a driver program?p44**
使用一個單獨的源代碼文件,其中包含一個名為 main 的函數來測試classes
**9. What will be shared among all objects of a certain class? What won't be shared so that each object owns for itself? Explain.**(p49)
will shared:靜態成員和函數, 因為成員之間共享。
won't be shared:非靜態成員變數和函數,因為成員與特定對象相關聯。
**10. Give an example class to show the separation of interface from implementation.**
```cpp=
#include <iostream>
using namespace std;
class Name
{
private:
string firstName;
string lastName;
public:
void setName(string, string);
void getName();
};
void Name::setName(string fName, string lName)
{
firstName = fName;
lastName = lName;
}
void Name::getName() {
cout << firstName << " " << lastName;
}
```
**11. Give the class definition without implementation for the following UML class diagram:**
```cpp=!
#ifndef GRADEBOOK_H
#define GRADEBOOK_H
#include <string>
class GradeBook {
public:
explicit GradeBook(std::string);
void setCourseName(std::string);
std::string getCourseName()const;
void displayMessage()const;
private:
std::string courseName;
};
#endif
```
(p.31~35)
**12. Give a proper implementation for the class definition.**
**13. Briefly describe the roles of class interface and class implementation.**(p.52 ~ p.54)
- `class interface` 負責提供整個 `class` 的功能和傳入及回傳值型態,讓人們更快速的了解這個 `class` 每個 `member function` 的作用
- `class implementation` 就是真正的 `class` 實作,把他從 `class interface` 分離出來也可以防止 `class` 的實作被隨便的修改
# CH17
*1-6誼,7-13安,14-20吉,21-26晨,27-32婕*
**1. How to prevent the multiple inclusion of class header? Show how it works?**(gpt)
```cpp=
#ifndef HEADER_FILENAME_H
#define HEADER_FILENAME_H
// 這裡是標頭檔案的內容
#endif // HEADER_FILENAME_H
```
當標頭檔第一次被包含時,預處理器會檢查 HEADER_FILENAME_H 是否已經定義。如果尚未定義,則會定義它並包含該檔案的內容。
當標頭檔再次被包含時,預處理器會發現 HEADER_FILENAME_H 已經定義,因此會跳過該檔案的內容,避免重複定義。
舉例:
MyClass.h
```cpp=
#ifndef MYCLASS_H
#define MYCLASS_H
class MyClass {
public:
MyClass();
~MyClass();
void myFunction();
};
#endif // MYCLASS_H
```
main.cpp
```cpp=
#include "MyClass.h"
#include "MyClass.h" // 再次包含
int main() {
MyClass obj;
obj.myFunction();
return 0;
}
```
**2. Show the result of the following statements:**(gpt)
```cpp
int x = 2, y = 15, z = 667;
cout << setfill( '0' ) << setw(2) << x << ":" << setw(4) << y << ":" << setw(3) << z << endl;
```
02:0015:667
**3. How to `inline` a member function?**(p15)
defined a member function in the class's body
**4. Give two advantages of member functions over conventional functions in non-object-oriented programs.**(gpt)
1.成員函數可以訪問和操作私有資料成員,保護資料不被外部直接修改,提高了程式的安全性和可維護性
2.成員函數與類別的資料和行為緊密相關,增加程式碼的結構性和可讀性
**5.What are the three ways to access the public class members outside a class's scope? Use the class `Example` with a public data member `item` for example.**(gpt)
1.透過物件實例(使用點運算子 (.))
```cpp=
#include <iostream>
class Example {
public:
int item;
};
int main() {
Example obj; // 創建類的實例
obj.item = 10; // 設置公共成員
std::cout << obj.item << std::endl; // 輸出公共成員
return 0;
}
```
2.透過指向物件的指標(使用箭頭運算子 (->))
```cpp=
#include <iostream>
class Example {
public:
int item;
};
int main() {
Example* ptr = new Example(); // 動態創建類的實例
ptr->item = 20; // 設置公共成員
std::cout << ptr->item << std::endl; // 輸出公共成員
delete ptr; // 釋放動態分配的記憶體
return 0;
}
```
3.透過物件的引用(使用點運算子 (.),因為引用本質上是一個別名)
```cpp=
#include <iostream>
class Example {
public:
int item;
};
int main() {
Example obj; // 創建類的實例
Example& ref = obj; // 創建對該實例的引用
ref.item = 30; // 設置公共成員
std::cout << ref.item << std::endl; // 輸出公共成員
return 0;
}
```
**6. How to access a data member in a member function containing a local variable of the same name to such data member? Use the class `Example` with a data member `item` for example.**(gpt)
用this指針
```cpp=
#include <iostream>
class Example {
public:
int item; // 類的資料成員
void setItem(int item) { // 成員函數,帶有與資料成員同名的局部變數
this->item = item; // 使用 this 指針訪問資料成員
}
void printItem() const {
std::cout << "item: " << item << std::endl; // 輸出資料成員
}
};
int main() {
Example obj;
obj.setItem(42); // 設置資料成員
obj.printItem(); // 輸出資料成員
return 0;
}
```
**7. Briefly describe the roles of access function and utility function.**
access function : can read or display data.
utility function : also called a helper function, is a private member function that supports the operation of the class’s other member functions
(p.25)
**8. Given a class `Triplet` with three data members of type `double`. Given an appropriate constructor having three parameters with default arguments of 0 for such class.**
class Triplet{
public:
double a;
double b;
double c;
Triplet(double a, double b, double c):a(0), b(0), c(0){}
};
**9. Briefly describe delegating constructor?**
it delegates its work to another constructor.(將工作委託給另一constructor)(p.36)
**10. Given a constructor of class `Triplet : Triplet(int, int, int)`. How to use it as a member initializer to construct delegating default constructor?**
Triplet::Triplet():Triplet(0, 0, 0){}(p.37)
**11. Briefly describe the role of a destructor.**
Called implicitly when an object is destroyed.(p.38)
**12. When will the sonstructor be called for objects in global scope, local scope, and static local objects?**(p.40~42)
global scope:在任何其他函式(包誇main)執行前
local scope:each time execution enters the scope of the object.(執行時)
static local objects:only once, when execution first reaches the point where the object is defined(只有一次,在執行第一次到達所定義的物件時)**
**13. When will the destructor be called for objects in global scope, local scope, and static local objects?**(p.40~42)
global scope:當main結束時
local scope:each time execution leaves the scope of the object(執行結束)
static local objects:s called when main terminates or the program calls function exit.(執行結束或遇到exit函數)
例外:函數 exit 會強制程式立即終止,並且不會執行本地物件的解構函數。函數 abort 的功能與 exit 類似,但強制程式立即終止,且不允許任何物件的解構函數被調用。
**14. Answer the following questions about invoking the destructor:**
**a) Under what circumstances, global objects will not invoke their destructor?**(p.40)
- 當程式呼叫 `exit` 或是 `abort` 時,則 `destructor` 不會被呼叫
**b) Under what circumstances, automatic local objects will not invoke their destructor?**(p.41)
- 當程式呼叫 `exit` 或是 `abort` 時,則 `destructor` 不會被呼叫
**c) Under what circumstances, static local objects will not invoke their destructor?**(p.42)
- 當程式呼叫 `abort` 時,則 `destructor` 不會被呼叫
**15. Why we should not return a reference or pointer to a private data member?**(p.47)
因為這將會破壞程式碼的封裝性,使得外部程式也可以透過這個function來隨便更改`private data member` 的內容
**16. What is the default assignment of assignment operator(=) for objects of the same type? When shouldn't we use it?**(p.52)
- 是一個memberwise的assignment(又稱called copy assignment),在等號(=)右邊的object的所有`data member`都會複製到等號(=)左邊相對應的 `data member`
- 當一個class裡面的 `data member` 包含動態分配記憶體的指標時就不該直接使用等號(=)
**17. What will occur when we pass an object as a function arguments?**(p.56)
預設會使用pass-by-vlaue,複製一整個物件之後傳入
**18. What will occur when we return an object from a function?**
預設會使用pass-by-vlaue,複製一整個物件之後回傳
**19. How can we declare a const member function?**(p.57)
```cpp=
const Time noon(12, 0, 0);
```
**20. Since a const object cannot be modified, why can they be created and destroyed by the constructor and the destructor?**(gpt)(p.60)
構造函數和析構函數在對象的生命週期的兩個不同階段發揮作用:
構造函數:在對象完全構建之前運行,因此可以初始化 const 成員。
析構函數:在對象即將銷毀時運行,用於清理資源,不涉及對象狀態的修改。
這使得 const 對象能夠在構造函數中被設置,在析構函數中被安全地銷毀。const 限制僅適用於對象構造完成後的狀態修改,而不適用於構造和析構過程中的初始化和清理工作。
**21. Briefly describe the term composition in C++.**(p.66)
將class作為member使用在另一個class。這種關係被稱為has-a關係
**22. What will happen if you don't use the member initializer list for some member objects? What if those objects have no default constructor?**(p.76)
1. the member object’s default constructor will be called implicitly
預設的constructor會被隱式調用
2. 會程式錯誤。
**23. Give the definition of friend functions and friend classes.**(p.78)
可以存取public和non-public class members 的 non-member function。可以是單獨的function、class或是member function of other classes
**24. How to declare a friend function and a friend class? Give an example for both situations.**
在前面加上friend
```cpp=
friend void function();
friend class friendclass;
```
**25. Give a short dexcription of the `this` pointer.**(p.84)
使用this pointer ,每個物件都可以存取自己的地址
**26. Give three capabilities provided by the `this` pointer.**
1. access to its own address (p.84)
2. Avoid naming collisions避免命名衝突(p.85)
3. Enable Cascaded Function Calls鏈式函式調用(p.90)
*ascaded Function Calls:在同一條語句中連續使用member function
**27. How to use the `this` pointer to access data member in a member function implicitly and explicitly? Use an example to demonstrate use answer.**

**28. What is the type of the `this` pointer?**

**29. How to use the `this` pointer to enable cascaded function calls?**

**30. Briefly describe the static data members.**

**31. How to access static class members?**

**32. How to accress the public static data members counter and public static member function `addCount` of class Example without any object of the class?**

# CH18
*13、15安,16、17婕,18、19誼,22、24晨,25吉*
**1. Show the result of the following statements:**
```
string a ( "Final Exam" );//初始化一個字符串 a,其值為 "Final Exam"
string b ( a );//初始化一個字符串 b,其值與 a 相同,即 "Final Exam"
b += (b.substr(6) + a.substr(0, 6));
//b.substr(6) 提取從位置 6 開始的 b 的子字符串。所以,b.substr(6) 的值是 "Exam"。
//a.substr(0, 6) 提取從位置 0 開始且長度為 6 的 a 的子字符串。所以,a.substr(0, 6) 的值是 "Final "。
//這些子字符串相連接:"Exam" + "Final " 結果是 "ExamFinal "
//+= 運算符將 "ExamFinal " 附加到 b。由於 b 最初是 "Final Exam",所以它變成 "Final ExamExamFinal "
cout<< b << endl;
```
Final ExamExamFinal
**2. Give three operators which can work on class objects without defining their overloaded operators.**
賦值運算符(=)
地址運算符(&)
逗號運算符(,)
**3. What cannot be changed when designing overloaded operators?**
運算符的優先順序、結合性、元數(arity)、語義含義
**4. What kinds of overloaded operators must be declared as class member?**
賦值運算符(=)、下標運算符([])、遞增和遞減運算符(++ 和 --)、函數調用運算符(())、成員訪問運算符(->)
**5. Describe the two ways to overload unary and binary operators.**
1.成員函數重載:將重載函數作為類的成員函數定義,調用對象出現在運算符的左邊(對於二元運算符)或者單獨出現(對於一元運算符)
2.非成員函數重載:將重載函數作為普通函數定義,運算符的操作數作為函數的參數,可以使得操作數不必是同一類型的對象
**6. Show how to overload the stream insertion and extraction operators using non-member friend function for a class with two private members of type integer (number) and type double (reward). You must give the class definition and separate the class implementation. The overloaded stream insertion and extraction operators must provide cascaded input and output.**
example.h
```cpp=
#ifndef EXAMPLE_H
#define EXAMPLE_H
#include <iostream>
class Example {
private:
int number;
double reward;
public:
Example(int num, double rew);
friend std::ostream& operator<<(std::ostream& os, const Example& obj);
friend std::istream& operator>>(std::istream& is, Example& obj);
};
#endif // EXAMPLE_H
```
example.cpp
```cpp=
#include "example.h"
Example::Example(int num, double rew) : number(num), reward(rew) {}
std::ostream& operator<<(std::ostream& os, const Example& obj) {
os << "Number: " << obj.number << ", Reward: " << obj.reward;
return os;
}
std::istream& operator>>(std::istream& is, Example& obj) {
is >> obj.number >> obj.reward;
return is;
}
```
**7. When should we overload an operator through a non-member function?**
對稱操作、轉換操作、不同類型的二元運算符、不依賴類狀態的操作、全局操作、內建類型的現有運算符
當使用到不同類型的對象時
**8. If we want to build a class with two private members of type `double` which represent the x and y coordinates. For such a class, show how to overload the `+` operator so that the x and y coordinates are added separately, and also make a cascaded addition possible. You must give the class definition and separate the class implementation.**
*要初始化嗎??
coordinates.h
```cpp=
class Coordinates
{
public:
Coordinates();
Coordinates(double , double );
Coordinates operator+(const Coordinates right)const;
private:
double x;
double y;
}
```
coordinates.cpp
```cpp=
#include "Coordinates.h"
Coordinates::Coordinates():x(0), y(0)
{
}
Coordinates:Coordinates(double xx, double yy):x(xx), y(yy)
{
}
Coordinates Coordinates::operator+(const Coordinates right) const {
double sumx = x+right.x;
double sumy = y+right.y;
return Coordinates(sumx, sumy);
}
```
**9. Show the compiler's view when a class object called prefix (++object) and postfix (object++) increment when the operators are overloaded through member and non-member functions.**
member function:
* ++object:
```cpp=
ClassName& operator++();
```
* object++:
```cpp=
ClassName operator++(int );
```
nom-member function:
* ++object:
```cpp=
ClassName& operator++(ClassName& obj);
```
* object++
```cpp=
ClassName operator++(ClassName& obj, int);
```
**10. Give the prototypes of the two member functions for overloading prefix and postfix decrement operators.
Suppose the prefix decrement is implemented by a member function, while the postfix decrement is implemented by a non-member function.**
```cpp=
ClassName& operator--();
ClassName operator--(ClassName& obj, int);
```
**11. A class `Int2d` contains two private members `dim1` and `dim2` of type integer. The postfix increment operator will return the original value and increase both the two integers one. Give the definition of such overloaded operator as a non-member function.**
```cpp=
Int2d operator++(Int2d& obj, int)
{
Int2d temp;
temp.dim1++;
temp.dim++;
return temp;
}
```
**12. Why we would prefer prefix rather than postfix increment/decrement for user-defined class?**(p.34)
profix造成額外的值可能會造成系統效能的問題
**13. Give an appropriate member function prototype for the overloaded assignment operator. Also give the definition of the overloaded assignment operator with two members `size_t length` and `double *dPtr`, where the overloaded assignment operator copies length elements of type double stored in the dynamic allocated memory space pointed by `dPtr`.**(p.51、52)
class String{
public:
String& operator=(const String& other);
private:
size_t length;
double *dPtr;
};
String &String::operator=(const String& other){
if(this != &other){
delete[]dPtr;
length = other.length;
dPtr = new doublr[other.length];
for(size_t i = 0; i < length; i++){
dPtr[i] = other.dPtr[i];
}
}
return *this;
}
**14. Briefly describe the functionality of `new` and `delete`.**(p.45)
`new`:dynamically allocate (i.e., reserve) the exact amount of memory required to hold an object or built-in array at execution time動態分配所需的記憶體
`delete`:return memory to the free store釋放記憶體
**15. Use `new` to allocate a space for a class object (not array) and store it to a proper variable. Also use `delete` to release the space.**(p.46)
(class Time)
Time *time = new Time();
delete time;
**16. Use `new` to allocate a space for an array of ten class objects and store it to a proper variable. Also use `delete` to release the space.**

**17. Given the following statements:**
```
Example * ptr= new Example;
delete ptr;
delete ptr;
````
**What will occur after executing the statements? How to fix it? Explain your answer.**

**18. Allocate a 20-element integer array dynamically, and initialize each element to zero. This should be done in a single statement.**
```cpp=
int* array = new int[20]{}; // 分配一個包含 20 個元素的整數陣列,並將每個元素初始化為零
```
**19. Show the problem of the following statements:**
```
char * ptr= new char[5];
delete ptr;
```
**Explain your answer.**
```cpp=
char* ptr = new char[5];
delete[] ptr;
```
使用 delete[] 避免記憶體洩漏和未定義的行為
**20. Give the three situations that a copy constructor will be invoked.**(p66)
1. pass by value
2. return by value
3. copy initialization
**21. What should be provided in a class with dynamically allocated memory?**(gpt)
1. A copy constructor(複製建構函式)
2. An assignment operator(賦值運算子)
3. A destructor(解構函式)
4. A move constructor(移動建構函式)
5. A move assignment operator(移動賦值運算子)
**22. Consider the user-defined class `Array` with two private data members (`size_t length` and `char * ptr`), please overload the square bracket `[]` operator so that it can be used to access (get and set) each array element. Make sure that the contents of a constant object will never be modified, and throw an exception if such access is illegal.**
**23. Why should we declare the constructor with a single argument as explicit?**(p89)
prevent implicit conversions(防止隱式轉換)
**24. Give an explicit conversion operator to convert the user-defined Array class (with a private data member `ptr` of type `double*`) to a `double` pointer.**
**25. Consider the user-defined class `Array2D` with three private data members (`size_t nrow`, `size_t ncol`, and `double **ptr`), please overload the function call operator `()` so that it can be used to access (get and set) each array element. Make sure that the contents of a constant object will never be modified, and throw an exception if such access is illegal.**(copilot)
```cpp=
#include <stdexcept>
class Array2D {
private:
size_t nrow;
size_t ncol;
double **ptr;
public:
// Assume constructors, destructors, and other methods are defined...
// Overload the function call operator for non-const objects
double& operator()(size_t row, size_t col) {
if (row >= nrow || col >= ncol) {
throw std::out_of_range("Index out of range");
}
return ptr[row][col];
}
// Overload the function call operator for const objects
const double& operator()(size_t row, size_t col) const {
if (row >= nrow || col >= ncol) {
throw std::out_of_range("Index out of range");
}
return ptr[row][col];
}
};
```
# CH19
*3、4安,5、6婕,7、8誼,9、10晨,11、12吉*
**1. Distinguish the is-a and has-a relationships.**(p5)
1. is-a 關係表示繼承,has-a 關係表示組合
2. 在 is-a 關係中,an object of a derived class也可以被視為an object of its base class
**2. Use example code to show the is-a and has-a relationships.**
```cpp=
#include <iostream>
using namespace std;
// 範例:is-a關係 (繼承)
class Animal {
public:
void speak() {
cout << "動物發聲" << endl;
}
};
class Dog : public Animal {
public:
void bark() {
cout << "狗叫" << endl;
}
};
// 範例:has-a關係 (組合)
class Engine {
public:
void start() {
cout << "引擎啟動" << endl;
}
};
class Car {
private:
Engine engine;
public:
void drive() {
cout << "汽車行駛中" << endl;
}
void startEngine() {
engine.start();
}
};
int main() {
// is-a關係示範
Animal animal;
Dog dog;
animal.speak(); // 輸出: 動物發聲
dog.speak(); // 輸出: 動物發聲
dog.bark(); // 輸出: 狗叫
// has-a關係示範
Car car;
car.drive(); // 輸出: 汽車行駛中
car.startEngine(); // 輸出: 引擎啟動
return 0;
}
```
**3. Draw the class hierarchy and show type of inheritance (single / multiple) for the following statements:Employee and Student both are a sort of Community member. For Employee, it can be of Faculty or Staff, while for Student, it can be of Undergraduate or Graduated. Not only Administrator is Faculty, but also Teacher is Faculty. Beyond that, Administrator teacher is Teacher, in the meantime it is Administrator.**(p.8)
```
CommunityMember
/ \
Employee Student
/ \ / \
Faculty Staff Undergraduate Graduated
/ \
Administrator Teacher
| |
AdministratorTeacher
```
(上到下)
**4. Give three advantages of inheritance over copy-and-paste approach when designing a new class.**
修改較容易,可讀性較高,可維護性較高
**5. Why is it preferred to initialize an object of a derived class by invoking the base-class constructor in the member initializer list?**

**6. Show the problem of the following code and give two ways to fix it.**
```cpp
class Foo
{
int x;
public:void setX(int y) { x = y; }
int getX() const { return x; }
};
class Bar : public Foo
{
public:
int output { return x; }
};
```

**7. A derived class using public inheritance can directly access the protected data members of its base class. Give two reasons not to use this method.**(gpt)
會破壞封裝性,增加代碼的依賴性和脆弱性
**8. Give an advantage of using private data member in the base class for designing derived classes.**(gpt)
保持封裝性,隱藏實現細節,並防止derived classes直接訪問數據成員
**9. How to invoke a redefined base-class member function from a derived class?**
**10. Suppose class Bar inherits from class Foo, and both classes have data members of other objects. Show how their constructors and destructors are called when an object of class Bar is declared.**
**11. Give three members that a derived class will not inherit.**(p.31)
- Constructor -- 每個 `class` 都必須有自己的constructor
- Destructor -- 每個 `class` 都必須有自己的destructor
- overloaded assignment operators
>However, derived-class **constructors**, **destructors** and **overloaded assignment operators** can call base-class versions.
**12. Show access levels of base class's members according to different base-class member access specifiers and different types of inheritance.** (p.64)
||public inheritance|protect inheritance|private inheritance|
|-|-|-|-|
|**public** Base-class member|public|protect|private|
|**protect** Base-class member|protect|protect|private|
|**private** Base-class member|can't access|can't access|can't access|
# CH20
*1-3安,4-6婕,7-9誼,10-12晨,13-15吉*
**1. What is polymorphism? What kinds of handles off which polymorphism works?**
不同資料型態使用同一個介面;透過基礎類別的指標、參考,而非類別名稱,compiler會判斷物件的資料型態來決定呼叫哪個相同名稱的member fuction。
**2. Give two advantages of polymorphism.**
程式彈性高、擴充性好(p.5)
**3. Considering the following four conditions:**
**1) base-class pointer aims at base-class object,**
**2) base-class pointer aims at derived-class object,**
**3) derived-class pointer aims at base-class object, and**
**4) derived-class pointer aims at derived-class object. Show the corresponding member functions invoked by virtual and non-virtual functions off the above four pointer handles.**(p.7~30)
1)無論是否為virtual都呼叫base-class.
2)non-virtual呼叫base-class;virtual呼叫derived-class.
3)未定義行為(derived-class object is a base-class object,but base-class is not sure a derived-class).
4)無論是否為virtual都呼叫derived-class.
**4. Show the results of the following code:**
```cpp
class Foo
{
public:
void output1() const { cout<< "Foo1" << endl; }
virtual void output2() const { cout<< "Foo2" << endl; }
};
class Bar : public Foo
{public:
void output1() const { cout<< "Bar1" << endl; }
virtual void output2() const override { cout<< "Bar2" << endl; }
void output3() const { cout<< "Bar3" << endl; }
};
Bar bar;
Foo *fooPtr= &bar;
```
**a) `fooPtr->output1();`**
**b) `fooPtr->output2();`**
**c) `fooPtr->output3();`**

**5. Suppose a base-class pointer is aimed at a derived-class object. How to call a derived-class-specific operation off such pointer? Explain.**

**6. Explain why we should add override to every overridden function in a derived class.**

**7. Show how to perform dynamic binding for a class Example with member function test.**
```cpp=
#include <iostream>
class Base {
public:
virtual void test() {
std::cout << "Base::test() 被呼叫" << std::endl;
}
};
class Derived : public Base {
public:
void test() override {
std::cout << "Derived::test() 被呼叫" << std::endl;
}
};
int main() {
Base* basePtr;
// 創建一個 Derived 對象
Derived derivedObj;
// 將 Derived 對象的地址賦值給基類指針
basePtr = &derivedObj;
// 動態繫結
// 根據實際對象類型呼叫適當版本的 test
basePtr->test();
return 0;
}
```
**8. Show the results of the following code:**
```cpp
class Animal
{
public:
virtual void behavior() const = 0;
};
class Cat : public Animal
{
virtual void behavior() const override { cout<< "Mew" << endl; }
};
class Dog : public Animal
{
virtual void behavior() const override { cout<< “Woof" << endl; }
};
class Chihuahua : public Dog
{
virtual void behavior() const override { cout<< " Woof-Woof-Woof" << endl; }
};
Cat cat;
Dog dog;
Chihuahua chihuahua;vector<Animal*> animalVec(3);
```
**a) `animalVec[0] = &cat; animalVec[0]->behavior();`**
輸出 `Mew`
**b) `animalVec[1] = &dog; animalVec[1]->behavior();`**
輸出 `Woof`
**c) `animalVec[2] = &chihuahua; animalVec[2]->behavior();`**
輸出 `Woof-Woof-Woof`
**9. When do we need a virtual destructor? Explain.**(gpt)
在有多態行為和動態內存分配的類層次結構中使用,確保 derived classes 透過基類指針(base class pointer)被正確銷毀,實現動態資源的正確清理。
**10. When do we need a virtual constructor? Explain.**
**11. Show how to prevent a class from being inherited. Also show how to prevent a member function from being overridden. Suppose the class is named as Example, and the function is named as test with no parameter.**
**12. Why polymorphic programming can eliminate switch logic?**
**13. Distinguish between abstract and concrete classes. Give one example for each type.**(p.34)
Abstract Classes沒有實例化任何的object,而能夠用來實例化object的class稱為concrete classes
```cpp!
// an example
class Shape // A abstract class
{
public:
virtual void draw() = 0;
};
class Circle : public Shape // A concrete class
{
public:
void draw() override {
cout << "Draw a circle" << endl;
}
};
```
**14. What's the main difference between virtual and pure virtual functions? Under what circumstances we should consider to declare a pure virtual function.**(p.37)
- 一個virtual function具有實作,並且給予derived class一個overriding的選項
- 一個pure virtual function不具有實作,且要求derived class要重寫函數,使derived class具體化
```cpp
virtual void draw() const = 0; // pure virtual function
virtual void draw() const; // virtual funciton
```
> 如果一個derived class不重寫所有abstract class的virtual function,將會使derived class本身也變成一個abstract class(p.37)
**15. Distinguish between implementation inheritance and interface inheritance.**(chat gpt)
**實作繼承(Implementation Inheritance)**
定義:
實作繼承是指派生類從基類繼承方法的實作,即派生類可以直接使用基類中已經定義好的方法。
特點:
- 繼承實作:派生類繼承基類的方法實作,可以重用基類的行為。
- 重載或覆寫:派生類可以重載(Overload)或覆寫(Override)基類的方法,以提供不同或新增的行為。
- 代碼重用:實作繼承主要用於代碼重用,減少重複代碼的編寫。
**介面繼承(Interface Inheritance)**
定義:
介面繼承是指派生類從基類繼承方法的定義(通常是純虛擬方法),即派生類只繼承方法的宣告,而必須自己提供具體的實作。
特點:
- 繼承介面:派生類繼承基類的方法定義(介面),但不繼承具體實作。
- 強制實作:派生類必須實作基類中定義的所有純虛擬方法。
- 多態性:介面繼承主要用於實現多態性,使不同的類可以有不同的具體實作,但具有相同的操作介面。
**總結**
- 實作繼承:強調代碼重用和行為重用,允許派生類直接使用或覆寫基類的方法實作。
- 介面繼承:強調多態性和接口一致性,派生類只繼承方法的定義,必須提供具體實作。