且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++重载转换运算符,用于将自定义类型转换为std :: string

更新时间:2022-11-18 21:29:29

该错误试图解释的是,如果也是std::string,或者t是[const] char*.您的转换运算符可以将t转换为任意一个,因此编译器没有选择另一个的基础....

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<std::string>(t);

或者您只能提供一种转换,并在必要时让用户进行进一步的转换.

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

尽管,您可能会发现-最后,任何转换运算符都比它值得的麻烦更多……这表明std::string本身并未为const char*提供转换运算符.

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*.