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

bookCombining Structs and Enums

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

Combining enums with structs gives you a powerful way to model real-world entities. By placing an enum inside a struct, you can represent not only the data but also the state or category of that data. For instance, you might use an enum to represent a person's gender or a task's status within a struct. This approach makes your code more expressive and less error-prone, since the enum restricts the possible values for that piece of information. Instead of using plain integers or strings, which can be misused or mistyped, enums make your intent clear and your data safer.

main.cpp

main.cpp

copy
12345678910111213141516171819202122232425262728293031323334
#include <iostream> #include <string> struct Task { enum Status { Todo, InProgress, Done }; std::string description; Status status; }; std::string statusToString(Task::Status status) { switch (status) { case Task::Todo: return "Todo"; case Task::InProgress: return "In Progress"; case Task::Done: return "Done"; default: return "Unknown"; } } int main() { Task task1; task1.description = "Write report"; task1.status = Task::InProgress; std::cout << "Task: " << task1.description << std::endl; std::cout << "Status: " << statusToString(task1.status) << std::endl; }

When you use enums inside structs, you gain type safety, which helps prevent bugs. By keeping the enum closely tied to the struct, you make it clear that the enum values are only meaningful within the context of that struct. This organization reduces the risk of mixing up unrelated enums and makes your code easier to understand and maintain. Always use enums to represent a fixed set of possible values for a struct member, and prefer defining the enum inside the struct unless it will be shared across multiple types.

question mark

What is a key advantage of defining an enum inside a struct?

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

すべて明確でしたか?

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

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

セクション 3.  3

AIに質問する

expand

AIに質問する

ChatGPT

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

セクション 3.  3
some-alt