C++: Structs
These lessons have covered quite a lot of C++ stuff; however I seem to have somehow missed out the struct!
A struct is basically a data structure, you treat struct objects a bit like objects from a C++ class (In fact in a lot of ways structs are like classes).
You can create a struct using the struct keyword like so:
struct struct_name{
int memberone;
float memberone;
};
In this case the struct is called "struct_name" (very creative I know) and it has two members, memberone and membertwo; You can have as many members as you want in a struct, and they can be of various types.
Then we end the struct with a closing curly bracket followed by a semicolon.
Just so we can work a bit more closely with structs, lets just create the following struct as an example:
struct Food{
int weight;
float price;
};
The struct above will be used to store various foods, which each have a weight and a price.
You create a struct object like you would create a variable:
Food apple;
Obviously in the case above we are creating an object called "apple".
We can then assign values for the different members of our struct to our object (give it a weight and price).
We do this by using a "." between the variable and the member of the variable we want to assign a value to, for example:
apple.weight = 12; apple.price = 30;
After assigning these values we can simply treat "apple.weight" and "apple.price" as normal variables; and do all sorts of things with them.
Here is a simple program which tells you information about an apple and a doughnut:
#include <iostream>
using namespace std;
struct Food{
int weight;
float price;
};
int main(){
Food apple;
Food doughnut;
cout << "Welcome to the apple and doughnut shop!\n\n"
apple.weight = 18;
apple.price = 30;
cout << "The apple's weight is: " << apple.weight << endl;
cout << "The apple's price is: " << apple.price << endl;
doughnut.weight = 10;
doughnut.price = 50;
cout << "The doughnut's weight is: " << doughnut.weight << endl;
cout << "The doughnut's price is: " << doughnut.price << endl;
system("PAUSE");
return 0;
}
Back to C++

