Skip to content

cpp_implicit_constructs

ShenYj edited this page Nov 15, 2023 · 1 revision

隐式构造

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

class Person {
    int m_age;
public:
    Person() {
        cout << "Person() - " << this << endl;
    }
    Person(int age) :m_age(age) {
        count << "Person(int) - " this << endl; 
    }
    Person(const Person &person) {
        cout << "Person(const Person &person) - " << this << endl;
    }

    ~Person() {
        count << "~Person() - " << this << endl; 
    }
};

void test1(Person person) {

}

Person tests2() {
    return 40;
}

int main() {

    Person p1;      /// 调用无参构造函数
    Person p2(10);  /// 调用有参构造函数
    Person p3 = p2; /// 调用拷贝构造函数

    /// ------ 重点 --------

    /// 等价于 Person p4(20) -》寻找Person类中只有一个int类型参数的构造函数
    Person p4 = 20; /// 调用了单参数的构造函数 

    /// ------ 重点 --------
    test1(30);      /// 调用了单参数的构造函数 同上↑

    /// ------ 重点 --------
    test2();        /// 调用了单参数的构造函数 同上↑

    /// ------ 重点 --------
    Person p5;      /// 不带参的构造函数
    p5 = 50;        /// 右边调用单个参数的构造函数赋值给左边 产生一次隐式构造覆盖了前面 
}

可以通过关键字explicit禁止掉隐式构造

class Person {
    int m_age;
public:
    Person() {
        cout << "Person() - " << this << endl;
    }
    explicit Person(int age) :m_age(age) {
        count << "Person(int) - " this << endl; 
    }
    Person(const Person &person) {
        cout << "Person(const Person &person) - " << this << endl;
    }

    ~Person() {
        count << "~Person() - " << this << endl; 
    }
};

void test1(Person person) { }

Person tests2() {
    /// 报错
    return 40;
}

int main() {
    /// 报错
    test(40)
}

Getting Started

Social

Clone this wiki locally