User Defined Conversions in C++

前端 未结 4 1997
遥遥无期
遥遥无期 2020-12-10 14:07

Recently, I was browsing through my copy of the C++ Pocket Reference from O\'Reilly Media, and I was surprised when I came across a brief section and example regard

4条回答
  •  一向
    一向 (楼主)
    2020-12-10 14:52

    Is this a particularly obscure feature?

    Yes, conversion operators aren't used very often. The places I've seen them are for user-defined types that can degrade to built-in ones. Things like a fixed-precision number class that supports converting to/from atomic number types.

    Is this relatively portable?

    As far as I know, it is. They've been in the standard forever.

    Can user-defined conversions to user defined types be done?

    Yes, that's one of the features of constructors. A constructor that takes a single argument effectively creates a conversion operator from the argument type to your class's type. For example, a class like this:

    class Foo {
    public:
        Foo(int n) {
            // do stuff...
        }
    }
    

    Let's you do:

    Foo f = 123;
    

    If you've used std::string before, odds are you've used this feature without realizing it. (As an aside, if you want to prevent this behavior, declare any single-argument constructors using explicit.)

提交回复
热议问题