- #include <iostream>
- using namespace std;
- class Test1 //类1
- {
- public:
- Test1(int n)
- { num = n; //普通的构造函数,可以进行隐式转换
- }
- private:
- int num;
- };
- class Test2 //类2
- {
- public:
- explicit Test2(int n)
- { num = n; //explicit(显式)构造函数,禁止隐式转换
- }
- private:
- int num;
- };
- int main()
- { Test1 t1 = 12; //类1隐式调用其构造函数, 成功
- // Test2 t2 = 12; //类2不能隐式调用其构造函数,因此编译错误,
- Test2 t3(12); //类2的显式调用初始化成功
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/2010201410674.html
来源: http://www.codesnippet.cn/detail/2010201410674.html