explicit关键字的用途:用来修饰构造函数避免隐式转换。
#include <iostream>
using namespace std;
class a
{
public:
a(int c){b = c;};
void show(){cout << b << endl;};
private:
int b;
};
int main()
{
a bb = 1;
bb.show();
return 0;
}
运行结果:
[root@localhost tmpc++]# ./s7
1
#include <iostream>
using namespace std;
class a
{
public:
explicit a(int c){b = c;};
void show(){cout << b << endl;};
private:
int b;
};
int main()
{
a bb = 1;
bb.show();
return 0;
}
运行结果:
[root@localhost tmpc++]# g++ s7.cpp -o s7
s7.cpp: In function ‘int main()’:
s7.cpp:13: 错误:请求从‘int’转换到非标量类型‘a’