windows

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));

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值