C++ overloading conversion operator for custom type to std::string

前端 未结 5 727
無奈伤痛
無奈伤痛 2020-12-30 03:52

I hope someone might be able to answer why the following doesn\'t work. Bear with me though, I am still very much a noob... I just cannot get to the bottom of why the follow

5条回答
  •  执笔经年
    2020-12-30 04:38

    What the error is trying to explain is that your assignment "s = t", where s is a std::string, would be valid if t were a std::string too, or if t were a [const] char*. Your conversion operators can convert a t into either, so the compiler has no basis on which to choose one over the other....

    You can disambiguate this explicitly by selecting the conversion you want:

    s = t.operator std::string();
    s = static_cast(t);
    

    Or you can provide only one of the conversions and let the user do a further conversion when necessary.

    You may find though - in the end - that any conversion operator is more trouble than it's worth... it's telling that std::string itself doesn't provide a conversion operator to const char*.

提交回复
热议问题