// 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;
}
CPP详解关键字 explicit
最新推荐文章于 2024-01-14 13:36:09 发布