C++ structs
Created By: chatGPT
Structs in C++ are a way to group related variables together into a single unit. They allow you to create user-defined data types to represent complex data structures. Let's look at an example of how to define and use structs in C++.
struct Person {
std::string name;
int age;
float height;
};
In the example above, we have defined a struct called Person that contains three member variables:
name
, age
, and height
. Now you can create instances of this struct to store personal information.int main() {
Person person1;
person1.name = "Alice";
person1.age = 30;
person1.height = 5.6;
Person person2;
person2.name = "Bob";
person2.age = 25;
person2.height = 5.9;
return 0;
}
You can also define a constructor inside your struct to initialize member variables at the time of creating an instance. This makes the code cleaner and ensures that your variables are set correctly.
struct Person {
std::string name;
int age;
float height;
Person(std::string n, int a, float h) {
name = n;
age = a;
height = h;
}
};
Here's how you would use the constructor to create instances of Person:
int main() {
Person person1("Alice", 30, 5.6);
Person person2("Bob", 25, 5.9);
return 0;
}
You can also create an array of structs for dealing with multiple records. For instance, if you want to keep a list of Person structs, you can easily do so.
int main() {
Person people[3];
people[0] = Person("Alice", 30, 5.6);
people[1] = Person("Bob", 25, 5.9);
people[2] = Person("Charlie", 28, 5.8);
return 0;
}
To access or modify the members of a struct, use the dot operator. For example, to print out the details of each person in the array we just created, you can use the following code:
int main() {
for (int i = 0; i < 3; i++) {
std::cout << "Name: " << people[i].name;
std::cout << ", Age: " << people[i].age;
std::cout << ", Height: " << people[i].height << "\n";
}
return 0;
}