构造函数已声明为explicit 为什么复制构造函数里还是可以隐式转换哪?
程序如下 带一个参数string的构造函数已声明为explicit 为什么复制构造函数里还是可以隐式转换哪?
- C/C++ code
#include <iostream>#include <string>using namespace std;class Employee{private: string name; int ID; static int cnt;public: Employee() {} explicit Employee(string nam) { cnt++; name=nam; ID=cnt; } Employee(const Employee& obj) { name=obj.name; ID=obj.ID; } Employee& operator=(const Employee &rhs) { name=rhs.name; ID=rhs.ID; return *this; } void printf() { cout<<ID<<" "<<name<<endl; } };int Employee::cnt=0;int main(){ Employee emp("adam"); Employee emp1=emp; string na="bill"; Employee emp2(na); emp.printf(); emp1.printf(); emp2.printf(); return 0;}[解决办法]
[解决办法]
你这个显式转换是指不能从string类型显式为Employee类型。。
- C/C++ code
void TestFunc(const Employee& e){ //...}string name = "tom";TestFunc(name);//编译不通过,Employee的转换构造函数必须要显式使用TestFunc(Employee(name));//编译通过