---
# System prepended metadata

title: C++ Week 04 structure and class
tags: [c++_beginner]

---

###### tags: `c++_beginner`
# Week 04
> 這周是類別和繼承，是我以前完全沒碰過的領域，一樣也是一起加油吧!

1. [structure](https://www.youtube.com/watch?v=9j5KkOC_goQ)

<iframe width="560" height="315" src="https://www.youtube.com/embed/9j5KkOC_goQ?si=PNLAQx73wsRPJ3kB" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>

2. [Class+Inheritance](https://www.youtube.com/watch?v=wN0x9eZLix4&t=276s)

<iframe width="560" height="315" src="https://www.youtube.com/embed/wN0x9eZLix4?si=8aJmx-d_W0sQsHFf" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>

3. [Operator Overloading](https://www.youtube.com/watch?v=BnMnozsSPmw)
<iframe width="560" height="315" src="https://www.youtube.com/embed/BnMnozsSPmw?si=PadCHgcJVd5HRNNb" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>

## Structure
### 講解
就像C一樣，structure的概念就是創造自己的資料類別的感覺，而我們可以定義自己的資料類別裡有哪些變數。
宣告:
```cpp=
struct Book{
    int ID;
    string title;
    string author;
    int year;
};
```
初始化:
```cpp=
int main() {
    Book book01;
    book01.ID=1001;
    book01.title="Mrs Dalloway";
    book01.author="Virginia Woolf";
    book0.year=1925;
    return 0;
}
```
### 題目
1. [Structs](https://www.hackerrank.com/challenges/c-tutorial-struct/problem?isFullScreen=true)

## Class
### 講解
類似於struct的東西，但是，他可以擁有自己的函數，而且可以使用 Inheritance 和 Operator Overloading 來操作變數，使寫程式更便利。
**宣告:**
```cpp=
class Person {// The class
private:// Access specifier
    char Gender;// Attribute
public:
    int Age;
    string Name;
    
    Person(int age,string name,char gender){//Constructors
        Age=age;
        Name=name;
        Gender=gender;
    }
    
    void Introduction() {//Class Methods
        cout << "Hello! My name is "<<Name<<endl;
    }
};
```
**使用:**
```cpp=
int main(){
    Person Jason=Person(17,"Jason",'b');//Call the constructors and set the attributes
    Jason.Introduction();//Call the class method: Introduction()
    cout<<Jason.Age<<endl;//There won't be any bug because this attribute is public
    cout<<Jason.Gender<<endl;//There will be a bug because this attribute is private
}
```
#### Access specifier
Access specifiers define how the members (attributes and methods) of a class can be accessed
* public: members are accessible from outside the class
* private: members cannot be accessed (or viewed) from outside the class
* protected: members cannot be accessed from outside the class, however, they can be accessed in inherited classes. You will learn more about Inheritance later.

#### Constructors
A constructor in C++ is a special method that is automatically called when an object of a class is created.

#### Class Methods
Methods are functions that belongs to the class.

There are two ways to define functions that belongs to a class:
* Inside class definition
```cpp=
class MyClass {        // The class
public:              // Access specifier
    void myMethod() {  // Method/function defined inside the class
        cout << "Hello World!";
    }
};

int main() {
    MyClass myObj;     // Create an object of MyClass
    myObj.myMethod();  // Call the method
    return 0;
}
```
* Outside class definition
```cpp=
class MyClass {        // The class
public:              // Access specifier
    void myMethod();   // Method/function declaration
};

// Method/function definition outside the class
void MyClass::myMethod() {
    cout << "Hello World!";
}

int main() {
    MyClass myObj;     // Create an object of MyClass
    myObj.myMethod();  // Call the method
    return 0;
}
```

### 題目
1. [Class](https://www.hackerrank.com/challenges/c-tutorial-class/problem?isFullScreen=true)
2. [Classes and Objects](https://www.hackerrank.com/challenges/classes-objects/problem?isFullScreen=true)

## Operator Overloading
### 講解
在使用Class時，我們偶爾會遇到想要直接把他們相加或比較的時候，這時直接使用 "+" 或 "==" 就會出現報錯，因為我們的函式庫不知道怎麼將他們比較。這時，我們就需要Operator Overloading 的技巧。
以下以cout為例。
```cpp=
void operator<<(ostream& COUT, Person &p){
    COUT<<"Name : "<<p.Name<<endl;
    COUT<<"Age : "<<p.Age<<endl;
}
int main(){
    Person person=Person(7,"Abby",'g');
    cout<<person;
}
```
這樣就會輸出:
```
Name : Abby
Age : 7
```
### 題目
1. [Box It!](https://www.hackerrank.com/challenges/box-it/problem?isFullScreen=true)

## Inheritance
### 講解
在使用Class時，有時會遇到和其他類別有相同性質的時候，這時我們就可以使用 Inheritance。例如，我們有一個類別:
```cpp=
class Car{
public:
    string Name,Owner;
    int year;
};
```
這時問題來了，車子有分電動車和汽油車，那要如何分別展示電量和油量呢?
我們可以創建兩個新類別並繼承Car的內容。
```
class ElectricCar: public Car{
public:
    double Battery;
};
class GasolineCar: public Car{
public:
    double Oil_volume;
};
```
繼承的另一個特性是可以使用protected裡的變數及函式。
```cpp=
class factors{
public:
    virtual void display(){
        cout<<a<<" "<<b<<endl;
    }      
protected:
    int a,b;
};

class Times: public factors{
public:
    void read_input(){
        cin>>a>>b;
    }
    void display(){
        cout<<a*b<<endl;
    }
};
```
virtual 有點像預設的意思，而如果像上面的程式碼被重新定義而又想再用呢，就要用以下方法。
```cpp=
Times t;
t.factors::display();//cout<<a<<" "<<b<<endl;
t.display();//cout<<a*b<<endl;
```
而virtual 有第二種用法，強制繼承那個Class的Class有某一個函式。用法如下:
```cpp=
class Base {
public:
    virtual void func1() = 0;
};

class Derived : public Base {
public:
    virtual void func1() override {//Must exist in the code, or there will be a bug
        cout << "Derived func1\n";
    }
};
```
### 題目
1. [Inheritance Introduction](https://www.hackerrank.com/challenges/inheritance-introduction/problem?isFullScreen=true)
2. [Rectangle Area](https://www.hackerrank.com/challenges/rectangle-area/problem?isFullScreen=true)
3. [Multi Level Inheritance](https://www.hackerrank.com/challenges/multi-level-inheritance-cpp/problem?isFullScreen=true)

## Test
這周沒有題目，希望大家可以運用這4周學到的知識來製作一個program:)。(可合作)
下面我會介紹，我自己的作品也希望你們做完後可以分享。
### 01 種菜大師
約翰是種菜大師，她擁有5\*5的田地，還有三種種子，分別是小黃瓜、番茄和薑。
以下是他們的資訊


| 品種 | 成熟所需時間 | 價錢 |
| -------- | -------- | -------- |
|小黃瓜|2天|9.9|
|番茄|2天|15|
|薑|6天|99.9|

* 他們成熟後會在(成熟所需時間/2)天後腐爛，成為肥料。
* 在有肥料的土地上成長的作物的價格收成後會乘1.5倍。
* 如果作物提早收成就只剩一半的價格。

玩家有五種動作，每個動作都會花一天的時間(有100天的時間)。
1. **移動** - 可選擇往上下左右移動一格
2. **播種** - 選擇3種作物的其中一種種植
3. **收成** - 將作物收入包包中，如果包包內有已有十個作物，則丟掉第一份被收入包包中的作物
4. **販售** - 將包包內的物品販售並清空。
5. **跳過** - 直接到下一天

* [Code](https://github.com/Benny0w0Liu/Cplusplus_assignment/blob/main/Week04/example/Vegetable_master/Vegetable_master.cpp) 
* [Video Demo](https://youtu.be/u-fe_EYeRDk)


(處女作就先給你們了இдஇ)
### 02 踩地雷
如題，就是踩地雷
* [Code](https://github.com/Benny0w0Liu/Cplusplus_assignment/blob/main/Week04/example/Minesweeper/Minesweeper.cpp) 


{%hackmd @25H8NTF5SwujU3QUSA0oog/BkiNnsk56 %}