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;

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

9 Comments

Test::operator std::string() const just my 2c
what should I do If I want to assign pointer of Test class to std::string?
I'd recommend you don't. Or do this: std::string tmp = my_test; doSomething(&tmp);
I need to. I did not get your last comment answer. I have a pointer of my Test Class and I need to assign it to a string.
|
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.

2 Comments

you can make conversion operators explicit in C++11, so you'd have to write str = static_cast<std::string>(t); which is probably safer, even if it is more characters.
Note that some std classes are intended for inheritance, like e.g. the std exception classes. But most are not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.