explicit的用法

In C++ it is possible to declare constructors for a class, taking a single parameter, and use those constructors for doing type conversion. For example:

        class A {
        public:
                A(int);
        };

        void f(A) {}

        void g()
        {
                A a1 = 37;

                A a2 = A(47);

                A a3(57);

                a1 = 67;

                f(77);
        }
A declaration like:

        A a1 = 37;

says to call the A(int) constructor to create an A object from the integer value. Such a constructor is called a "converting constructor".

However, this type of implicit conversion can be confusing, and there is a way of disabling it, using a new keyword "explicit" in the constructor declaration:

        class A {
        public:
                explicit A(int);
        };

        void f(A) {}

        void g()
        {
                A a1 = 37;      // illegal

                A a2 = A(47);   // OK

                A a3(57);       // OK

                a1 = 67;        // illegal

                f(77);          // illegal
        }
Using the explicit keyword, a constructor is declared to be
"nonconverting", and explicit constructor syntax is required:

        class A {
        public:
                explicit A(int);
        };

        void f(A) {}

        void g()
        {
                A a1 = A(37);

                A a2 = A(47);

                A a3(57);

                a1 = A(67);

                f(A(77));
        }

Note that an expression such as:

        A(47)

is closely related to function-style casts supported by C++. For example:

        double d = 12.34;

        int i = int(d);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值