C++隐式转换和explicit关键字

48 阅读1分钟

在学习c++的过程中又发现一个有趣的知识点。上代码

class Entity{
public:    
    Entity(){
        cout<< "Create Entity"<< endl;
    }

    Entity(int num){
        cout<< "Create Entity"<< num << endl;
    }
};
int main(){
    Entity* a = new Entity(1);
    Entity b = 2; //两种初始化方式都可行
    return 0;
}

c++的隐式转换,作为一个java开发者看到 Entity b = 2这种代码一脸懵逼,但 c++里面却可以这么用。而explicit关键字则是不允许这种隐式转换

class Entity{
public:    
    Entity(){
        cout<< "Create Entity"<< endl;
    }

    explicit Entity(int num){
        cout<< "Create Entity"<< num << endl;
    }
};
int main(){
    Entity* a = new Entity(1);
    //Entity b = 2; //不允许
    return 0;
}