Game Development Reference
In-Depth Information
sum.result = 0;
ReturnSum(sum);
cout << sum.result << endl;
return 0;
}
Listing 5-6 begins by defining our structure. We do this using the
struct
keyword. Immediately
after the keyword is the name we would like to use for our structure. This name behaves as though
we have created a new type. We can see this in the first line of
_tmain
where we declare the
variable
sum
.
Once we have a variable that is of a structure type, we can use the
.
operator to access its
member
variables. We assign the values 3, 6, and 0 to the members of
sum
and then pass it by reference
to the function
ReturnSum
. The compiler would have made a copy of all three members if we had
passed the structure by value and therefore we would not have been able to read the proper result of
the sum from the
result
member.
You can use the information you have learned about functions in this chapter to modify the game we
have been writing.
Adding Functions to Text Adventure
We began our Text Adventure game in Chapter 4. At that time you didn't know that we could store
data in structures or that we could use functions to make more readable programs. In this chapter
we will create a structure for the player and create a function that will be responsible for welcoming
the player. We do both of these in Listing 5-7.
Listing 5-7. Adding the Player
struct
and
WelcomePlayer
Function to Text Adventure
#include <iostream>
#include <string>
using namespace std;
struct Player
{
string m_name;
};
void WelcomePlayer(Player& player)
{
cout << "Welcome to Text Adventure!" << endl << endl;
cout << "What is your name?" << endl << endl;
cin >> player.m_name;
cout << endl << "Hello " << player.m_name << endl;
}