C++ Structures
In C++, a structure is a user-defined data type that groups together variables of different data types under a single name. Structures are useful when you need to group together data that belongs together. For example, you can use a structure to represent a person's name, address, and phone number.
Declaring a Structure in C++
To declare a structure in C++, use the struct
keyword followed by the structure name, followed by the structure definition within curly braces {}
. The structure definition contains variables that represent the members of the structure.
Example:
1struct Person 2{ 3 string name; 4 string address; 5 int age; 6};
In this example, we have declared a structure named Person
with three members: name
, address
, and age
.
Defining a Structure Variable
To define a structure variable, use the structure name followed by the structure variable name.
Example:
Person person1;
In this example, we have defined a structure variable named person1
of type Person
.
Accessing Members of a Structure
To access the members of a structure, use the structure variable name followed by the dot .
operator and the member name.
Example:
1#include <iostream> 2#include <string> 3using namespace std; 4 5struct Person 6{ 7 string name; 8 string address; 9 int age; 10}; 11 12int main() 13{ 14 Person person1; 15 person1.name = "William Max"; 16 person1.address = "123 Main Street"; 17 person1.age = 30; 18 19 cout << "Name: " << person1.name << endl; 20 cout << "Address: " << person1.address << endl; 21 cout << "Age: " << person1.age << endl; 22 23 return 0; 24}
Output:
1Name: William Max 2Address: 123 Main Street 3Age: 30
In this example, we have defined a structure variable named person1
and assigned values to its members name
, address
, and age
. We then access the members of the structure using the dot .
operator and print their values to the console.