#include <iostream>
using namespace std;
class student
{
public:
student(int age)
{
this->age = age;
}
student(string name, int age)
{
this->name = name;
this->age = age;
}
private:
string name;
int age;
};
int main()
{
//这种称为显式构造
student s1(10);
student s2("小明", 10);
//下面这种直接用赋值号给类成员初始化参数列表的,这种称为隐式构造,
//直接用赋值号给类成员初始化参数列表时,默认的使用隐式构造,C++11新增特性
student s3 = 10;
student s4 = { "小王", 10 };
return 0;
}
我们比较常用的是显示构造,但是用赋值符号时进行隐式构造时,这种情况下我们进行编译时没有没有任何问题的,一样可以执行
当我们在类的构造函数前面加上explicit关键字时,如下
#include <iostream>
using namespace std;
class student
{
public:
explicit student(int age)
{
this->age = age;
}
explicit student(string name, int age)
{
this->name = name;
this->age = age;
}
private:
string name;
int age;
};
int main()
{
//这种称为显式构造
student s1(10);
student s2("小明", 10);
//下面这种直接用赋值号给类成员初始化参数列表的,这种称为隐式构造,
//直接用赋值号给类成员初始化参数列表时,默认的使用隐式构造,C++11新增特性
student s3 = 10;
student s4 = { "小王", 10 };
return 0;
}
我们发现会报错,“student” 的复制列表初始化不能使用显式构造函数
这是因为我们在构造函数前添加explicit关键字时,该构造函数会被声明为显式构造函数,就无法进行隐式构造,即使用赋值号进行初始化成员函数的操作
如果我们没有声明explicit关键字时,默认显式构造和隐式构造都可以进行成员初始化操作
我们的问题也来了,那么为什么会产生explicit关键字呢?有什么用呢?
原来:explicit关键字是为了防止隐式使用拷贝构造函数进行初始化类成员
为什么要这样做呢?
使用explicit可以防止发生混淆,因为这个符号‘ = ’ 我们一般看做赋值号,但是在开发项目时,特别是多人开发的项目时,特别是参与二次开发的项目,如果代码量很多的时候,看到这个符号很容易愣住,到底是赋值呢?还是构造呢?
这会导致开发效率和代码可阅读力下降
所以有些团队或公司,明确必须使用显示构造,也防止二次开发的人员进行隐式构造的操作,在构造函数前调加explicit关键字,避免后续开发中出现的问题
。。。。。。