开发者

Constructor: is it the right one being called?

In your opinion, which constructor will be called?

class Element {
public:
    Element(bool b = true, bool c = true);
    Element(const std::string s, bool b = true, bool c = true);
};
...
Element element("something", true);

Wrong! The first one.

Do I have to restart Stroustrup's book from the beginning?

I tried without the const, but nothing changes.

It seems that a char* looks more like a bo开发者_开发技巧ol than a std::string.

With this code everything is all right:

Element element(string("something"), true);

Compiler: Microsoft Visual C++ 2010

OS: Windows 7


There is a built-in conversion from pointer types to bool, non-null pointers are converted to true and null pointer values to false.

std::string is a user-defined type (in the loosest sense of the word user) so the conversion from const char* to std::string won't be preferred over the built-in const char* to bool conversion. You have to do something like this (or add an overload which takes a const char *).

Element element( std::string("something"), true);


.

C++ Standard (N1905) says,

$4.1 Standard conversions are implicit conversions defined for built-in types. Clause 4 enumerates the full set of such conversions. A standard conversion sequence is a sequence of standard conversions in the following order:

[...]

— Zero or one conversion from the following set: integral promotions, floating point promotion, integral conversions, floating point conversions, floating-integral conversions, pointer conversions, pointer to member conversions, and boolean conversions.

[...]

$4.4 In general, an implicit conversion sequence (13.3.3.1) consists of a standard conversion sequence followed by a user-defined conversion followed by another standard conversion sequence.

4.12 Boolean conversions

$4.12.1 An rvalue of arithmetic, enumeration, pointer, or pointer to member type can be converted to an rvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false any other value is converted to true.

13.3.3.2 Ranking implicit conversion sequences

2 When comparing the basic forms of implicit conversion sequences (as defined in 13.3.3.1)

a standard conversion sequence (13.3.3.1.1) is a better conversion sequence than a user-defined conversion sequence or an ellipsis conversion sequence, and

— a user-defined conversion sequence (13.3.3.1.2) is a better conversion sequence than an ellipsis conversion sequence (13.3.3.1.3).

Hope, it explains well the behaviour shown by your code. :-)

Also, this is a good read :

Implicit conversion sequences (C++ only)

.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜