Try   HackMD

C++ 隨手筆記#6

前一篇 C++ 隨手筆記#5

建構子Constructor

甚麼是建構子

在定義類別(class)時,我們可以使用建構子來對物件進行初始化。並且在創建該物件時,會自動調用建構子

使用方法

要創建建構子,必須使用跟類別一樣的名稱,然後 括號()

#include <iostream>
#include <string>
using namespace std;

class Player
{
    public:
        Player()
        {
            cout << "Hello World!" << endl;
        }
}

int main()
{
    Player mylayer;
    system("pause");
}

顯示結果

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

   TIPS
          這邊要加上public:的原因為類別預設為private


   TIPS
          建構子與類別具有相同的名稱,且沒有任何回傳值

建構參數

建構子同樣可以採用參數,這對於設置屬性的初始值非常有幫助。如同下方範例,當我們傳遞參數時,建構子會將參數的值同步到屬性

#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");
    }

顯示節果

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

外部定義

在了解外部定義之前,我們要先認識一個新符號 ::,稱作作用域符。不要被它響亮霸氣的名稱給震懾到了,它的使用方法其實很簡單。如果在程式中的某一處你想要調用類別的屬性或是建構子,那麼就會使用到作用域符

回到正題,建構子同樣可以在類別外部定義,但是要先在類別內宣告建構子

使用方法

類別 :: 建構子

#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