放牧代码和思想
专注自然语言处理、机器学习算法
    This thing called love. Know I would've. Thrown it all away. Wouldn't hesitate.

C++ 关键字explicit

explicit表示禁止自动类型转换,作用于单参数构造函数。又是一个比较冷门的关键字:

#include <iostream>
using namespace std;

class Foo
{
public:
	Foo()
	{
		cout << "Foo constructed" << endl;
	}
	Foo(int n)
	{
		cout << "Foo constructed with " << n << endl;
	}
};

class Child:public Foo
{
public:
	explicit Child(int n)
	{
		Foo::Foo(n);
	}
};

///////////////////////////SubMain//////////////////////////////////
int main(int argc, char *argv[])
{
	Foo f(0);
	f = 1;

	Child c(2);
	// won't compile
	// c = 3;

	system("pause");
	return 0;
}
///////////////////////////End Sub//////////////////////////////////

知识共享许可协议 知识共享署名-非商业性使用-相同方式共享码农场 » C++ 关键字explicit

评论 欢迎留言

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

我的作品

HanLP自然语言处理包《自然语言处理入门》