Why is my overloaded C++ constructor not called?

前端 未结 6 1715
暖寄归人
暖寄归人 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:07

    When you have a constructor (especially multiple constructors) that take only a single argument, it may be suitable to declare them "explicit" to avoid these kind of surprises. This forces the user of the class to make sure he gives the correct type to the constructor he wishes to use and prevents these implicit type conversions from being done behind the users back and hiding hard to find bugs.

    http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=15&rll=1

    In C++0x, this has been extended to conversion operators to prevent the same issue

    http://www2.research.att.com/~bs/C++0xFAQ.html#explicit-convertion

提交回复
热议问题