Why does C++ allow an integer to be assigned to a string?

前端 未结 4 2165
长情又很酷
长情又很酷 2020-11-27 06:32

I encountered an interesting situation today in a program where I inadvertantly assigned an unsigned integer to a std::string. The VisualStudio C++ compiler did not give an

4条回答
  •  没有蜡笔的小新
    2020-11-27 07:05

    The std::string class has the following assignment operator defined:

    string& operator=( char ch );
    

    This operator is invoked by implicit conversion of unsigned int to char.

    In your third case, you are using an explicit constructor to instantiate a std::string, none of the available constructors can accept an unsigned int, or use implicit conversion from unsigned int:

    string();
    string( const string& s );
    string( size_type length, const char& ch );
    string( const char* str );
    string( const char* str, size_type length );
    string( const string& str, size_type index, size_type length );
    string( input_iterator start, input_iterator end );
    

提交回复
热议问题