Overloaded Bool/String Ambiguity

前端 未结 4 974
陌清茗
陌清茗 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条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-02 05:56

    With

    A(string("hello"));
    

    it will give the expected result.

    Why is it so ?

    It's because of the standard conversions:

    • "hello" is understood as a const char* pointer
    • this pointer can be converted to a bool (section 4.12 of the standard: "A prvalue of (...) pointer (...) type can be converted to a prvalue of type bool." )
    • the conversion from "hello" to string is not considered because section 12.3 of standard explains that "Type conversions of class objects can be specified by constructors and by conversion functions. These conversions are called user-defined conversions" and "User-defined conversions are applied only where they are unambiguous". Wouldn't you have the bool constructor the std::string conversion would be done implicitely.

    How to get what you expected ?

    Just add the missing constructor for string litterals:

    A(const char* v)
    {
        cout << v;  // or convert v to string if you want to store it in a string member
    }
    

    Of course, instead of rewriting a constructor from scratch, you could opt for a delegate as suggested by 0x499602D2 in another answer.

提交回复
热议问题