C++中存在隐式构造现象,某些情况下会调用单参数的构造函数。

    1. #include <iostream>
    2. class Cat {
    3. int m_age;
    4. public:
    5. Cat(){
    6. std::cout << "Cat()" << std::endl;
    7. };
    8. Cat(int age = 0):m_age(age){
    9. std::cout << "Cat(int age = 0):m_age(age)" << std::endl;
    10. };
    11. Cat(const Cat &cat):m_age(cat.m_age){
    12. std::cout << "Cat(const Cat &cat):m_age(cat.m_age)" << std::endl;
    13. }
    14. };

    外界创建Cat对象

    1. Cat cat1 = 10; //此时会调用单参数的构造函数,等价与 Cat cat1 = Cat(10);

    这就是隐式构造。
    还有一个比较好的例子

    1. void test(Cat cat1){ //相当于Cat cat1 = 10;
    2. }
    3. Cat test1(){
    4. return 10; //会隐式构造
    5. }
    6. int main(int argc, const char * argv[]) {
    7. test(10); //调用
    8. test1(); //调用
    9. return 0;
    10. }

    这种隐式的调用单参的构造函数很没有可读性。所有C++给我们提供了一个explicit关键字来禁止这种行为。

    1. class Cat {
    2. int m_age;
    3. public:
    4. Cat(){
    5. std::cout << "Cat()" << std::endl;
    6. };
    7. explicit Cat(int age = 0):m_age(age){
    8. std::cout << "Cat(int age = 0):m_age(age)" << std::endl;
    9. };
    10. Cat(const Cat &cat):m_age(cat.m_age){
    11. std::cout << "Cat(const Cat &cat):m_age(cat.m_age)" << std::endl;
    12. }
    13. };

    禁止后下面的代码会直接报错
    image.png