I’d really like to be able to assign a std::string object from a DecoratedString object that I’m writing.
class DecoratedString
{
private:
std::string m_String;
public:
DecoratedString(const std::string& initvalue)
: m_String(initvalue)
{
}
const std::string& ToString() const
{
return m_String;
}
const std::string& operator=(const DecoratedString& rhs)
{
return rhs.ToString();
}
}
I’ve written a unit test to make sure this works:
void DecoratedStringTest::testAssignmentToString()
{
std::string expected("test");
DecoratedString sut(expected);
std::string actual;
actual = sut;
CPPUNIT_ASSERT_EQUAL(actual, sut.ToString());
}
However, the compiler says error: no match for 'operator=' in 'actual = sut'. It then lists the overloaded operator= options from the standard library.
Why isn’t the compiler finding the operator= I defined?
EDIT:
So I guess I need a conversion operator, not an assignment operator. Huge thanks to the people that saw what I was trying to do and explained what I should do instead.
The operator = you have defined is for assigning decorated strings to other decorated strings and returning an std::string from that assignment.
What you want is a member “conversion operator” that automatically converts a decorated string to an std::string whenever required, like this:
That will also convert a decorated string automatically to a
std::string const &whenever one is needed (i.e. when comparing to an std::string, or passing a DecoratedString to a function which takes astd::string const &).