2

I want to have a class like below:

Class Test {
  Test();
  ~Test();
  ...
}

I want to be able to use following statement:

std::string str;
Test t;
str = t;

what should I do? should I override to_string? If yes it seems that it is not possible to inherit from std::string class. Or I have to override special operator? What about Pointer assignment? like below:

std::string str;
Test* t = new Test();
str = t;
JGC
  • 12,737
  • 9
  • 35
  • 57

2 Answers2

7

You can provide a user-defined conversion operator to std::string:

class Test {
  //...
public:
  operator std::string () const {
    return /*something*/;
  }
};

This will allow a Test object to be implicitly-converted to a std::string.

TartanLlama
  • 63,752
  • 13
  • 157
  • 193
2

Although in C++ it is possible, it is generally not advised to inherit from standard classes, see Why should one not derive from c++ std string class? for more info.

I am wondering, what is the function of the assignment of

str = t;

str is a std::string type, t is Test type. So what is the expected value of the assigment? No one can guess. I suggest to explicitly call a conversion method or an operator for code clarity.

This would make your example look like:

str = t.convertToString();

or the more standard way is to implement the stream operator, which makes

str << t;

(Note this example works if str is a stream type, if it is a string, you need further code, see C++ equivalent of java.toString?.)

But, if you really want it to work without a conversion method, you can override the string assignment operator of Test:

class Test {
public:
    operator std::string() const { return "Hi"; }
}

See also toString override in C++

Although this is a perfect solution to your question, it may come with unforeseen problems on the long run, as detailed in the linked article.

Community
  • 1
  • 1
Gee Bee
  • 1,794
  • 15
  • 17
  • you can make conversion operators explicit in C++11, so you'd have to write `str = static_cast(t);` which is probably safer, even if it is more characters. – Tom Tanner Feb 16 '16 at 12:20
  • Note that some std classes are intended for inheritance, like e.g. the std exception classes. But most are not. – Erik Alapää Feb 16 '16 at 12:42