why implicit conversion is harmful in C++

后端 未结 8 1647
臣服心动
臣服心动 2020-12-03 10:22

I understand that the keyword explicit can be used to prevent implicit conversion.

For example

Foo {

 public:
 explicit Foo(int i) {}
}
         


        
8条回答
  •  萌比男神i
    2020-12-03 10:35

    A real world example:

    class VersionNumber
    {
    public:
        VersionNumber(int major, int minor, int patch = 0, char letter = '\0') : mMajor(major), mMinor(minor), mPatch(patch), mLetter(letter) {}
        explicit VersionNumber(uint32 encoded_version) { memcpy(&mLetter, &encoded_version, 4); }
        uint32 Encode() const { int ret; memcpy(&ret, &mLetter, 4); return ret; }
    
    protected:
        char mLetter;
        uint8 mPatch;
        uint8 mMinor;
        uint8 mMajor;
    };
    

    VersionNumber v = 10; would almost certainly be an error, so the explicit keyword requires the programmer to type VersionNumber v(10); and - if he or she is using a decent IDE - they will notice through the IntelliSense popup that it wants an encoded_version.

提交回复
热议问题