关于关键字explicit 和 implicit

来源:互联网 发布:淘宝如何引流推广 编辑:程序博客网 时间:2024/05/22 08:27

这两个关键字从字面意思上,我们知道是"明确的" 和 “含蓄的,不言明”的意思,换成程序的说法是能否进行隐式转换

举个Unity LayerMask的例子

public struct LayerMask

{

     public static implicit operator int (LayerMask mask);//讲LayerMask隐式转换为int类型

     public static implicit operator LayerMask(int intval); //int 隐式转换转换为LayerMask类型

}

看看MSDN的例子

class Digit{    public Digit(double d) { val = d; }    public double val;    // ...other members    // User-defined conversion from Digit to double    public static implicit operator double(Digit d)    {        return d.val;    }    //  User-defined conversion from double to Digit    public static implicit operator Digit(double d)    {        return new Digit(d);    }}class Program{    static void Main(string[] args)    {        Digit dig = new Digit(7);        //This call invokes the implicit "double" operator        double num = dig;        //This call invokes the implicit "Digit" operator        Digit dig2 = 12;        Console.WriteLine("num = {0} dig2 = {1}", num, dig2.val);        Console.ReadLine();    }}

隐式转换可以通过消除不必要的类型转换来提高源代码的可读性。 但是,因为隐式转换不需要程序员将一种类型显式强制转换为另一种类型,所以使用隐式转换时必须格外小心,以免出现意外结果。 一般情况下,隐式转换运算符应当从不引发异常并且从不丢失信息,以便可以在程序员不知晓的情况下安全使用它们。 如果转换运算符不能满足那些条件

class Test1
{
public:
    Test1(int n)
    {
        num=n;
    }//普通构造函数
private:
    int num;
};
class Test2
{
public:
    explicit Test2(int n)
    {
        num=n;
    }//explicit(显式)构造函数
private:
    int num;
};
int main()
{
    Test1 t1=12;//隐式调用其构造函数,成功
    Test2 t2=12;//编译错误,不能隐式调用其构造函数
    Test2 t2(12);//显式调用成功
    return 0;
}


隐式转换常常在我们写代码中容易引起不容易觉察的错误,以及内存泄漏等




0 0
原创粉丝点击