Game Development Reference
In-Depth Information
void SetName(const std::string& name)
{
m_name = name;
}
const std::string& GetName() const
{
return m_name;
}
void SetCurrentRoom(const Room* pCurrentRoom)
{
m_pCurrentRoom = pCurrentRoom;
}
const Room* GetCurrentRoom() const
{
return m_pCurrentRoom;
}
};
An assignment operator is passed a constant reference to the object that is being assigned from.
This allows you to copy all of the relevant fields to the object being assigned to. There is a major
difference between a copy constructor and an assignment operator. A copy constructor is invoked
when a new object is being created and can be initialized by copying from an existing object. The
assignment operator is invoked when assigning to an already existing object. Listing 12-4 shows an
example.
Listing 12-4. Invoking an Assignment Operator
Player newPlayer;
newPlayer = m_player;
You can now use general arithmetic assignment operators with your classes so long as you remember
to overload the assignment operator appropriate for assigning to your class as in Listing 12-3.
Move Semantics
Move semantics are useful when dealing with some more complex C++ code. We'll cover some
cases where move semantics are useful later in this topic, but for now I'll show you how you can
add move constructors and move assignment operators to your classes. Move semantics differ
from normal copy constructors and assignment operators in that they operate on rvalue references.
An rvalue reference is denoted in C++ using a double ampersand. These rvalue references can only
be used when working with temporary objects, which can be created under many circumstances
in C++, such as when returning objects from functions by value. Listing 12-5 shows a move
constructor for the Player class.
 
Search WWH ::




Custom Search