windows

来源:互联网 发布:淘宝9秒视频制作软件 编辑:程序博客网 时间:2024/05/16 07:22

explicit在编程应用中的意义

      对构造函数起作用,举例:

#include <iostream>

usingnamespacestd;

classItem{ 

public: 

    inta; 

     Item(inta){ 

        this->a=a; 

    } 

    voidshow(){ 

        cout<<a<<endl; 

    } 

}; 

 

intmain(){ 

    Itemit=10; 

    it.show(); 

    it='a'; 

    it.show(); 

    return0; 

}

这个程序输出的结果分别为10 97,这样会造成不必要的错误,如果改成下面的程序

#include<iostream>

usingnamespacestd;

classItem{

public:

    inta;

     explicitItem(inta){

        this->a=a;

    }

    voidshow(){

        cout<<a<<endl;

    }

};

intmain(){

    inta=10;

//  Itemit=a;这样隐式转换是会报错的

    Itemit(10);

}

 

(3)为何Java没有explicit这个关键字

      在Java中给出了另外的一种实现方式(Java中的装箱),所谓的装箱,就是进行隐式的类型转化,把基本类型用它们相应的引用类型包装起来,使其具有对象的性质。int包装成Integer、float包装成Float,如下所示

publicvoidm12(){

    Integera=newInteger(128);

    Integerb=128;

    System.out.println("m12result"+(a==b));

}