# C++ 隨手筆記#6 >前一篇 [C++ 隨手筆記#5](https://hackmd.io/@Neroal/Sys5XWrrI) [TOC] ## 建構子Constructor ### 甚麼是建構子 在定義類別(class)時,我們可以使用建構子來對物件進行初始化。並且在創建該物件時,會自動調用建構子 ### 使用方法 要創建建構子,必須使用跟類別一樣的名稱,然後 **括號()** ```C++ #include <iostream> #include <string> using namespace std; class Player { public: Player() { cout << "Hello World!" << endl; } } int main() { Player mylayer; system("pause"); } ``` 顯示結果  <div style="background-color:#FFEE99;"> <b><font color="black">   TIPS</font></b> <br> <font color="black">          這邊要加上<b>public:</b>的原因為類別預設為<b>private</b><br></br> </font> </div> <br> <div style="background-color:#FFEE99;"> <b><font color="black">   TIPS</font></b> <br> <font color="black">          建構子與類別具有相同的名稱,且沒有任何回傳值<br></br> </font> </div> ## 建構參數 建構子同樣可以採用參數,這對於設置屬性的初始值非常有幫助。如同下方範例,當我們傳遞參數時,建構子會將參數的值同步到屬性 ```c++ #include <iostream> #include <string> using namespace std; class Player { public: string name; int lv; int hp; Player(string x,int y,int z) { name = x; lv = y; hp = z; } void PrintProperty() { cout << name << endl; cout << lv << endl; cout << hp << endl; } }; int main() { Player myplayer("Neroal",100,2000); myplayer.PrintProperty(); system("pause"); } ``` 顯示節果  ## 外部定義 在了解外部定義之前,我們要先認識一個新符號 **::**,稱作**作用域符**。不要被它響亮霸氣的名稱給震懾到了,它的使用方法其實很簡單。如果在程式中的某一處你想要調用類別的屬性或是建構子,那麼就會使用到作用域符 回到正題,建構子同樣可以在類別外部定義,但是要先在類別內宣告建構子 ### 使用方法 **類別** **::** **建構子** ```c++ #include <iostream> #include <string> using namespace std; class Player { public: string name; int lv; int hp; Player(string x, int y, int z); void PrintProperty() { cout << name << endl; cout << lv << endl; cout << hp << endl; } }; Player::Player(string x,int y,int z) { name = x; lv = y; hp = z; } int main() { Player myplayer("Neroal",100,2000); myplayer.PrintProperty(); system("pause"); } ``` ###### tags: `C++` `constructor`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up