string operator+ ( const string& s, const Dan& d )
{
return s + d.toString();
}
Since Dan doesn't have a suitable conversion to std::string, you also would need to provide another operator+ with the commutative operation:
string operator+ ( const Dan& d, const string& s )
{
return s + d.toString();
}
toString should also be const since it doesn't modify the state of your object:
string toString() const
{
return first + ", " + last;
}
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>I tried what you posted
No, you didn't. You tried some oddball variation of what I posted after filtering it through your n00b brain. Neither my code nor my comments suggested that operator+ should be a member function. Since toString is a public member function of Dan, neither of the overloads for operator+ should even be friends of Dan. Like this:
class Dan {
// Data members
public:
string toString() const;
// No operator+ here
};
string operator+ ( const string& s, const Dan& d )
{
return s + d.toString();
}
string operator+ ( const Dan& d, const string& s )
{
return s + d.toString();
}
>but it complains
I'm not surprised. When implemented as a member function, operator+ expects only one argument. When implemented as a non-member function, operator+ expects two arguments. The two are not interchangeable.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>and the insults not so much
I can live with that.
>Why do you think I need both?
Users of your class will rightfully expect Dan + string to work just as well as string + Dan. Of course, in hindsight I should have written:
string operator+ ( const Dan& d, const string& s )
{
return d.toString() + s;
}
Instead of pasting the body of the other operator+. This way users will get the expected behavior for string concatenation.
>I changed it to return the first + ", " + last directly
Not a good idea. Eventually you'll learn that public data members are a bad thing and make them private, then your code will break. You'll either have to use a public interface for the operators, or make them friends of your class. Both of those entail work on your part, so it's better to do it right from the start.
>since first and last are not const so I couldn't return them using the toString.
That shouldn't matter. A non-const object can be converted to a const object implicitly. The inverse is not true, but that's not the case here. Show me the code that's causing the error, preferably something I can compile directly so I don't accidentally fix something by writing framework code.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401