explicit 关键字修饰构造函数

经常我们看到,修饰构造函数的一种关键字  explicit 表示生成对像是需要显示调用构造函数。

如下例:

无explicit

#include <iostream>
using namespace std;
class B
{
public:
	B(){cout<<"constructor"<<endl;}
	B(int i):data(i){}
	~B(){cout<<"~destructor"<<endl;}
private:
	int data;
};

B Play(B b)
{
	return b;
}


int main()
{
	B temp = Play(6);//6-->B(6)发生了隐式转化
	return 0;
}
编译通过

运行输出:

~destructor
~destructor


有explicit

//============================================================================
// Name        : haha.cpp
// Author      :
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
using namespace std;
class B
{
public:
	B(){cout<<"constructor"<<endl;}
	explicit B(int i):data(i){}
	~B(){cout<<"~destructor"<<endl;}
private:
	int data;
};

B Play(B b)
{
	return b;
}


int main()
{
	B temp = Play(6);
	return 0;
}
编译:

error: could not convert '6' from 'int' to 'B'

此时自动类型转化,己不行。要生成对像,转过去必须显示的调用构造函数。

将其改成:

B temp = Play(B(6);编译可通过










版权声明:本文为linux_wgl原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。