C++ 補充 & C++ 11 - explicit 關鍵字

explicit 關鍵字

explicit /ɪkˈsplɪsɪt/ 明確的;清楚的;直率的;詳述的

作用是表明該構造函數是顯示的, 而非隱式的.不能進行隱式轉換! 跟它相對應的另一個關鍵字是implicit, 意思是隱藏的,類構造函數默認情況下即聲明爲implicit(隱式).

demo1 代碼:

#include <iostream>
#include <string>

using namespace std;

class student
{
public:
	student(int _age)
	{
		this->age = _age;
		cout << "arg=" << age << endl;
	}

	student(int _age, const string _name)
	{
		this->age = _age;
		this->name = _name;
		cout << "age=" << age << "; name=" << name << endl;
	}

	~student()
	{

	}

	int getAge()
	{
		return age;
	}

	string getName()
	{
		return name;
	}

private:
	int age;
	string name;

};


int main(void)
{
	student xiaoM(18); /* 顯示構造 */
	student xiaoW = 18; /* 隱式構造 */

	student xiaoHua(19, "小花"); /* 顯示構造 */
	student xiaoMei = { 18, "小美" }; /* 隱式構造 初始化參數列表, C++11 前編譯不能通過, C++11 新增特性 */

	system("pause");
	return 0;
}

demo2 代碼

#include <iostream>
#include <string>

using namespace std;

class student
{
public:
	explicit student(int _age)
	{
		this->age = _age;
		cout << "arg=" << age << endl;
	}

	explicit student(int _age, const string _name)
	{
		this->age = _age;
		this->name = _name;
		cout << "age=" << age << "; name=" << name << endl;
	}

	~student()
	{

	}

	int getAge()
	{
		return age;
	}

	string getName()
	{
		return name;
	}

private:
	int age;
	string name;

};


int main(void)
{
	student xiaoM(18); /* 顯示構造 */
	student xiaoW = 18; /* 隱式構造 */

	student xiaoHua(19, "小花"); /* 顯示構造 */
	student xiaoMei = { 18, "小美" }; /* 隱式構造 初始化參數列表, C++11 前編譯不能通過, C++11 新增特性 */

	system("pause");
	return 0;
}

這樣的話隱式就會報錯, 顯示就會沒問題.
在這裏插入圖片描述
在這裏插入圖片描述

結語:

時間: 2020-06-30

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章