explicit 关键字作用是表明该构造函数是显式的,而非隐式的,不能进行隐式转换,类构造函数默认情况下是隐式的。
#include <iostream>
#include <string>
using namespace std;
class Student
{
public:
explicit Student(int age)
{
m_age = age;
cout << "age = " << m_age << endl;
}
explicit Student(int age, const string name)
{
m_age = age;
m_name = name;
cout << "age = " << m_age << " name = " << m_name << endl;
}
~Student()
{
}
private:
int m_age;
string m_name;
};
int main()
{
Student xiaoM(18); //显式构造
//Student xiaoJ = 18; //隐式构造 默认情况下可以使用,但如果构造函数加了explicit关键字,这样使用会报错
Student xiaoH(18,"小花"); //显式构造
//Student xiaoMei = {18,"小美"}; //隐式构造,初始化参数列表,c++11前不能通过,c++11新增特性,如果构造函数加了explicit,会报错
system("pause");
return 0;
}