搜尋此網誌

2025年9月30日星期二

Using classes

Inventory myInventory(5);

Inventory → the name of a class (or struct) you’ve defined earlier.

myInventory → the name of the object (an instance of the class).

(5) → this calls a constructor of the class Inventory that takes an int parameter.

So this line means:

“Create an object called myInventory of type Inventory, and initialize it using the constructor that accepts the integer 5.”

myInventory.addItem("Arrow");

myInventory is an object of some class, say Inventory.
addItem() is a member function of that class.
"Arrow" is a string literal being passed as an argument.
So in C++, you’d typically define a class Inventory that stores items (maybe in a std::vector<std::string>), and then implement addItem() to push new items into that container.

The dot (.) operator is one of the most fundamental symbols in many programming languages, including C, C++, Java, and C#. Its main purpose is to access members (variables, methods, or properties) of an object, structure, or namespace.

When you create an object of a class, you use the dot operator to call its methods or access its fields.

In programming, when we say “call a method”, we mean asking the computer to run the block of code defined inside that method.

A method (or function) is a reusable block of code that performs a specific task.

To call a method is to execute it: the program jumps to that method, runs its instructions, and then comes back to continue where it left off.

Microsoft Copilot

沒有留言:

發佈留言