CPP详解关键字 explicit

// Explicit.cpp : Defines the entry point for the console application.
//	详解explicit关键字

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;
int obj_cnt = 0;
class Person {
public:
	int id;
	char name[ 10 ];
public:
	Person() {}
	/*explicit 
	// 表示初始化类的时候是显示的如 Person p(1),没有加的话可以隐性使用 Person p = 1
	*/ 
	Person( int id = 0 ) {
		this->id = id;

		cout << "隐性构造 by id,构造可以使用 Person p=1  或者 Person p(1) " << endl;
	}

	/* explicit 显性构造*/

	explicit Person( const char* name ) {
		strcpy( this->name , name );
		cout << "显示构造 by char*, 构造必须 Person p1( \"name\")  " << endl;
	}

	virtual ~Person() {
		obj_cnt++;
	}
};

void test() {
	// 隐性构造
	Person p = 1; 
	Person p2( 2 );
	// 显性
	Person p1( "fuck you" );
}
int main(int argc, char* argv[])
{
	// 调用函数,
	test();
	// 构造的对象个数
	cout << obj_cnt << endl;
}



已有 0 人发表留言,猛击->>这里<<-参与讨论


ITeye推荐



原文地址:https://www.cnblogs.com/qwop/p/3438439.html