Why is my overloaded C++ constructor not called?

前端 未结 6 1748
暖寄归人
暖寄归人 2021-02-20 12:17

I have a class like this one:

class Test{
public:
  Test(string value);
  Test(bool value);

};

If I create an object like this:



        
6条回答
  •  遇见更好的自我
    2021-02-20 13:08

    This is a well known C++ annoyance.

    Your string literal has type of chat const[]. You've got two constructors, conversion sequences from char const[] to Test look like this:

    1) char const[] -> char const* -> bool

    2) char const[] -> char const* -> std::string

    1) is a built-in standard conversion whereas 2) is a user-defined conversion. Built-in conversions have precedence over user defined conversions, thus your string literal gets converted more easily to bool than to std::string.

提交回复
热议问题