Overloaded Bool/String Ambiguity

前端 未结 4 979
陌清茗
陌清茗 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:54

    When selecting an overloaded method this is the order that the compiler tries:

    1. Exact match
    2. Promotion
    3. Standard numerical conversion
    4. User defined operators

    A pointer doesn't promote to bool but it does convert to bool. A char* uses an std operator to convert to std::string. Note that if char* used the same number in this list to convert to both bool and std::string it would be ambiguous which method the compiler should choose, so the compiler would throw an "ambiguous overload" error.

    I would throw my weight behind 0x499602D2's solution. If you have C++11 your best bet is to call: A(char* s) : A(std::string(s)){} If you don't have C++11 then I would create an A(char* s) constructor and abstract the logic of the A(std::string) constructor into a method and call that method from both constructors.

    http://www.learncpp.com/cpp-tutorial/76-function-overloading/

提交回复
热议问题