explicit 关键字

来源:互联网 发布:大数据 行业专家 编辑:程序博客网 时间:2024/06/05 22:59

C++中构造函数的作用有两个
1. 构造器
2. 默认且隐含的类型转换操作符
举个栗子:

class testClass{public:    testClass(void);    ~testClass(void);    testClass(int x)    {        m_ix = x;    }private:    int m_ix;    double *m_p;    double m_dy;};

主函数中会调用构造函数进行隐式转换:

testClass tc;tc = 1;

如果 加了关键字进行限制以后

class testClass{public:    testClass(void);    ~testClass(void);    explicit testClass(int x)    {        m_ix = x;    }private:    int m_ix;    double *m_p;    double m_dy;};

如刚才的调用方式就会编译不通过,报错信息:没有找到接受“int”类型的右操作数的运算符,无法进行隐式转换

0 0