C++ - Structure
In C++, a structure is a user-defined data type that allows you to combine different types of variables under a single name. Structures provide a way to group related data together, making it easier to organize and manipulate complex data structures. Here's how you can work with structures in C++:
Create a Structure:
To create a structure, you define its blueprint using the struct keyword, followed by the structure name and a block of member variables. Here's an example:
struct Person {
std::string name;
int age;
float height;
};
In this example, a structure named Person is defined with three member variables: name of type std::string, age of type int, and height of type float.
Access Structure Members:
You can access the individual members of a structure using the dot (.) operator. Here's an example:
Person person;
person.name = "John";
person.age = 25;
person.height = 175.5;
In this example, a variable person of type Person is created, and its members (name, age, and height) are accessed using the dot operator.
One Structure in Multiple Variables:
You can create multiple variables of the same structure type. Each variable will have its own set of member variables. Here's an example:
Person person1;
person1.name = "John";
person1.age = 25;
person1.height = 175.5;
Person person2;
person2.name = "Alice";
person2.age = 30;
person2.height = 165.0;
In this example, two variables person1 and person2 of type Person are created, and each variable has its own set of member variables.
Named Structures:
C++ allows you to create named structures by specifying a name immediately after the closing brace of the structure definition. Named structures can be used to create variables directly without explicitly using the struct keyword. Here's an example:
struct Person {
std::string name;
int age;
float height;
} person;
In this example, a named structure Person is defined, and a variable person of type Person is created.