explicit关键字

来源:互联网 发布:华元宠物用品淘宝真假 编辑:程序博客网 时间:2024/05/28 04:53

C++ explicit关键字用来修饰类的构造函数,表明该构造函数是”显式“的,默认构造函数是”隐式“的。

”隐式“具有自动转换功能,如果构造函数只有一个参数那么在编译的时候就会有一个缺省的转换操作,将该构造函数对应数据类型的数据转换成该类对象。

class Test

{

private:

        int m_intValue ;
        float m_floatValue ;

public:

        Test(int i)//隐式 构造函数

        {

                this->m_intValue = i ;

        }

        explicit Test(float f)//显式 构造函数

        {

                this->m_floatValue = f ;

        }

}


int main()

{

        Test t = 5 ;  //正确。等同于: Test temp(5); Test t = temp ;

        Test t1 = 2.0 //错误。必须为Test t1 = Test(2.0)

        return 0;

}

0 0
原创粉丝点击