Overloaded Bool/String Ambiguity

前端 未结 4 976
陌清茗
陌清茗 2021-01-02 04:57

Why is C++ casting the string literal I pass in as a bool rather than a string?

#include 

using namespace std;

class A
{
    public:
              


        
4条回答
  •  Happy的楠姐
    2021-01-02 05:39

    If you have C++11 you can use a delegating constructor:

    A(char const* s) : A(std::string(s)) { }
    

    The reason the boolean converting-constructor is chosen over the one for std::string is because the conversion from char const* to bool is a standard conversion while the one to std::string is a user-defined conversion. Standard conversions have a greater rank than user-defined conversions.

提交回复
热议问题