Game Development Reference
In-Depth Information
void SetName(const std::string& forename, const std::string& surname)
{
m_name = forename;
m_name.append(" ");
m_name.append(surname);
}
void SetName(const std::string& name)
{
m_name = name;
}
const std::string& GetName() const
{
return m_name;
}
};
Your Player class now contains two methods called SetName . You can call either of these methods
using the following lines:
player.SetName("Bruce Sutherland");
player.SetName("Bruce", "Sutherland");
The compiler automatically works out which of the two methods to call based on the parameters
being passed in. The first line here would call the method that simply assigns the string to m_name ;
the second line would call the function that assigns the first name then appends a space before
appending the surname. Both functions result in m_name storing the same string value.
Methods can only be overloaded by having different parameter types. Methods with different names
are not overloaded, but the code will still compile. Methods that only have different return types are
not allowed. Listing 8-10 shows an example of this.
Listing 8-10. SetName with Different Return Types
void SetName(const std::string& name)
{
m_name = name;
}
bool SetName(const std::string& name)
{
m_name = name;
return true;
}
If you try this in Visual Studio, you will see the following error:
error C2556: 'bool Player::SetName(const std::string &)' : overloaded function differs only by
return type from 'void Player::SetName(const std::string &)'
Search WWH ::




Custom Search