Приоритеты операторов неявного преобразования C ++
РЕДАКТИРОВАТЬ: после комментария Майка Сеймура я заменилoperator std::string () const;
сoperator char * () const;
и изменил реализацию соответственно. Это позволяет выполнять неявное приведение, но по какой-то причине неподписанный оператор long int имеет приоритет над оператором char *, который просто не выглядит правильным ... Кроме того, я не хочу показывать неприятные вещи C, такие как char *, вне класс, когда у меня есть std :: string. У меня есть догадка, что мой класс CustomizedInt должен унаследовать от некоторых вещей, чтобы поддержать функцию, которую я желаю. Может ли кто-нибудь разработать комментарий Майка относительноstd::basic_string
? Я не уверен, что правильно понял.
У меня есть этот кусок кода:
<code>#include <string> #include <sstream> #include <iostream> class CustomizedInt { private: int data; public: CustomizedInt() : data(123) { } operator unsigned long int () const; operator std::string () const; }; CustomizedInt::operator unsigned long int () const { std::cout << "Called operator unsigned long int; "; unsigned long int output; output = (unsigned long int)data; return output; } CustomizedInt::operator std::string () const { std::cout << "Called operator std::string; "; std::stringstream ss; ss << this->data; return ss.str(); } int main() { CustomizedInt x; std::cout << x << std::endl; return 0; } </code>
Который печатает & quot; Вызываемый оператор unsigned long int; 123 & Quot ;. У меня такие вопросы:
After I remove the operator unsigned long int, why do I need to cast x to std::string explicitly? Why does it not call the implicit cast operator (std::string) directly? Is there any documentation that explains which implicit casts are allowed and which is their order of precedence? It seems that if I add an operator unsigned int to this class together with the operator unsigned long int, I receive a compiler error about ambiguity for the << operator... Also, I know that defining such an operator may be poor practice, but I am not sure I fully understand the associated caveats. Could somebody please outline them? Would it be better practice to just define public methods ToUnsignedLongInt and ToString?