Thursday, September 24, 2009

Howto: C++ Class Conversion Operator in .CPP file

In case someone did not know how to do this. It took me some time to figure out the right syntax for writing conversion operator implementation in the CPP file. Here is the definition of the conversion operator.

In a header (.h) file we have TestCase class declared.

class TestCase
{
public:
    operator std::string ();
};
While in .CPP we should have declaration written in the form TestCase::.
The declaration of the "to std::string" conversion operator will look like this
TestCase::operator std::string()
{
   std::string msg("TestCase internals");
   return msg;
}
Now we can use this operator in the code
TestCase testClass;
std::string msg = testClass;
msg variable will be equal to "TestCase internals" string.

No comments:

Post a Comment