Game Development Reference
In-Depth Information
Our += operator is an assignment operator, which means we want to use it to modify our object.
You can see this in our operator method where we append the name string onto the object's m_name
member variable. We can use this in the following manner:
player.SetName("Bruce");
player += " Sutherland";
Sometimes you might not want to modify the object, but instead would like to add the name to the
passed string and store a returned value. It might make more sense to overload the + operator in this
instance. Listing 8-12 shows an example of this.
Listing 8-12. The Overloaded + Operator
std::string operator+(const std::string& name)
{
std::string output(m_name);
output.append(name);
return output;
}
This function appends the passed string parameter to the m_name member and returns the new string
that was created to store the result. We can use this operator in the following way.
player.SetName("Bruce");
string fullName = player + " Sutherland";
These examples are not the most useful and are being created just to show you how you can
incorporate operator overloading into your future classes. There's also a drawback to the examples
we have looked at: We cannot chain the operators together. Listing 8-13 shows an assignment
operator that allows chaining.
Listing 8-13. Operator Chaining
const Player& operator=(const Player& player)
{
m_name = player.name;
return *this;
}
The major new keyword being used in this example is this . The this pointer is a built-in keyword
that C++ supplies. It is a pointer that stores the address of the current object. Our = operator returns
a constant reference to the current Player object. Listing 8-14 alters our WelcomePlayer method to
show how this allows operator chaining in practice.
Listing 8-14. Operator Chaining
void WelcomePlayer(Player& player)
{
cout << "Welcome to Text Adventure!" << endl << endl;
cout << "What is your name?" << endl << endl;
Search WWH ::




Custom Search