Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Declaring and Initializing Structs | Struct Fundamentals
C++ Structures and Enumerations

bookDeclaring and Initializing Structs

メニューを表示するにはスワイプしてください

To declare a struct in C++, use the struct keyword followed by its name and curly braces containing member variables. Each member is declared like a normal variable and ends with a semicolon. Don’t forget the semicolon after the closing brace to complete the declaration.

Once defined, you can create variables of that struct type just like any other data type. Struct members can be initialized individually or with brace initialization to assign all values in order.

Note
Note

Brace initialization helps prevent errors by ensuring members are set in the correct order.

main.cpp

main.cpp

copy
1234567891011121314151617
#include <iostream> #include <string> struct Person { std::string name; int age; }; int main() { // Create and initialize a Person variable Person alice = {"Alice", 30}; // Print the values std::cout << "Name: " << alice.name << std::endl; std::cout << "Age: " << alice.age << std::endl; }

Once you have created an instance of a struct, you can access its members using the dot operator (.). The dot operator allows you to read or modify the value of a specific member field. For example, if you have a Person variable named alice, you can access the name member with alice.name and the age member with alice.age. To change a field, simply assign a new value to it using the same syntax. This approach makes it easy to update information stored in a struct after it has been initialized.

question mark

Which of the following correctly declares a struct?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  2

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  2
some-alt