搜尋此網誌

2025年10月22日星期三

Constructor

public:
    Person(const std::string& name, float energy, float happiness, float health)
        : name(name), energy(energy), happiness(happiness), health(health) {}

parameterized constructor with a member initializer list

Person(...) → Constructor for the Person class.

const std::string& name → Passes the string by reference (avoids copying) and const ensures it won’t be modified inside the constructor.

A reference is an alias for another variable. 

float energy, float happiness, float health → Parameters to initialize the object’s state.

: name(name), energy(energy), happiness(happiness), health(health) → This is the member initializer list.

It directly initializes the data members with the values passed in.

More efficient than assigning inside the constructor body, especially for complex types like std::string.

{} → Empty body, since all initialization is already done in the initializer list.

Microsoft Copilot

沒有留言:

發佈留言