C++关键字explicit的用法

C++关键字explicit,可以阻止不应该允许的经过转换构造函数进行的隐式转换的发生,声明为explicit的构造函数不能在隐式转换中使用。

 

C++中, 带有一个形参的构造函数(或者除了第一个参数外其余参数都有默认值的多参构造函数), 承担了两个角色。 

1 是类的带参构造函数;2 是默认且隐含的类型转换操作符。

比如一个类Class A, 有时候在我们写下如 A a= xxx, 这样的代码, 且恰好xxx的类型正好是类A的单参数构造器的参数类型, 这时候编译器就自动调用这个构造器, 创建一个A的对象。

请看下面代码:

Person.h:

#pragma once
#include "stdafx.h"
#include <string>

class CPerson
{
public:
    CPerson();
//    explicit CPerson(string strName);           //1处代码
//    CPerson(string strName);                        //2处代码

    ~CPerson();

    string getName();
    void setName(string strName);

    string getSex();
    void setSex(string strSex);

    int getAge();
    void setAge(int nAge);

    void showPerson();
private:
    string m_strName;
    int m_nAge;
    string m_strSex;
};

 

Person.cpp:

#include "stdafx.h"
#include "CPerson.h"


CPerson::CPerson()
{
}


CPerson::~CPerson()
{
}

CPerson::CPerson(string strName)
{
    m_strName = strName;
    m_nAge = 10;
    m_strSex = "男";
}


string CPerson::getName()
{
    return m_strName;
}

void CPerson::setName(string strName)
{
    m_strName = strName;
}


string CPerson::getSex()
{
    return m_strSex;
}


void CPerson::setSex(string strSex)
{
    m_strSex = strSex;
}


int CPerson::getAge()
{
    return m_nAge;
}

void CPerson::setAge(int nAge)
{
    m_nAge = nAge;
}

void CPerson::showPerson()
{
    cout << "Name:" << m_strName << endl;
    cout << "Age:" << m_nAge << endl;
    cout << "Sex:" << m_strSex << endl;
}

main.cpp:

// KeywordTest.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "CPerson.h"

int main()
{

    CPerson person("zzzzzzzzzzzzzzzzzz");
    cout << "person Age:"<<person.getAge() << endl;
    cout << "person--------------:" << endl;
    person.showPerson();


    cout << endl;
    CPerson person2 = string("wwwwwwwwwwwwwwwwww");
    cout << "person2--------------:" << endl;
    person2.showPerson();
    return 0;

}

用2处代码,没用explicit修饰单个参数的构造函数,代码没问题!

C++关键字explicit的用法

用1处代码,用explicit修饰单参数的构造函数,代码不能通过编译!

C++关键字explicit的用法

特别注意

          explicit只能写在声明中,不能写在定义中。