简体   繁体   中英

C++ conversion operator overload

'int' and 'double' conversion functions is 'explicit' and in this code why have I permit for use this conversion instead of error message? If I delete all my conversion overload functions code occur 'conversion error'

class Person
{
public:
    Person(string s = "", int age = 0) :Name(s), Age(age) {}
    operator string() const { return Name; }
    explicit operator int() const{ return 10; }  // ! Explicit
    explicit operator double()const { return 20; } //! Explicit
    operator bool()const { if (Name != "") return true; return false; } // using this
};

int main(){

    Person a;
    int z = a;
    std::cout << z << std::endl;   // Why print "1"?  Why uses bool conversion?
}

I this it is answer:

Because 'a' can not be convert to int or double it occur error, but because it has bool conversion function, which can convert to int and int to double, code use this function.

int z = a;

Looks innocuous, right?

Well, the above line calls the implicit bool-conversion-operator, because that's the only way you left it to get from Person to int , and that only needs one user-defined conversion (the maximum allowed).

This is the reason for the safe-bool-idiom before C++11, and the major reason for the general advice to mark conversion operators and single-argument ctors explicit unless they are not transformative nor lossy.

If you want to see it for yourself, fix your code and trace invocation of your operator bool .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM