首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

构造函数已声明为explicit 为什么复制构造函数里还是可以隐式转换哪?解决方案

2012-06-16 
构造函数已声明为explicit 为什么复制构造函数里还是可以隐式转换哪?程序如下 带一个参数string的构造函数

构造函数已声明为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;}


[解决办法]
探讨

("adam");这个是const char*转成string 和你这个explicit构造函数有毛关系

[解决办法]
你这个显式转换是指不能从string类型显式为Employee类型。。
C/C++ code
void TestFunc(const Employee& e){    //...}string name = "tom";TestFunc(name);//编译不通过,Employee的转换构造函数必须要显式使用TestFunc(Employee(name));//编译通过 

热点排行