38.C++拷贝构造函数调用时机和规则

拷贝构造函数调用时机

C++中拷贝构造函数调用时机通常有三种情况

  • 使用一个已经创建完毕的对象来初始化一个新对象
  • 值传递的方式给函数参数传值
  • 以值方式返回局部对象

示例:

#include<iostream>
using namespace std;

//C++中拷贝构造函数调用时机通常有三种情况

class Person
{
public:
    Person()
    {
        cout << "Person默认构造函数调用" << endl;
    }
    Person(int age)
    {
        m_age = age;
        cout << "Person有参构造函数调用" << endl;
    }
    Person(const Person& p)
    {
        cout << "Person拷贝构造函数调用" << endl;
        m_age = p.m_age;
    }
    ~Person()
    {
        cout << "调用析构函数" << endl;
    }
public:
    int m_age;
};
//1、使用一个已经创建完毕的对象来初始化一个新对象
void test01()
{
    Person p1(10);
    Person p2(p1);
    //观察拷贝函数
    cout << "p2的年龄为:" << p2.m_age << endl;
}
//2、值传递的方式给函数参数传值
void doWork(Person p )
{

}
void test02()
{
    Person p;
    doWork(p);//值传递就是传递的是临时拷贝的一个副本,所以就调用了拷贝构造函数
}
//3、以值方式返回局部对象
Person  doWork2()
{
    Person p1;
    return p1;//返回的时候根据P1创建出一个新的对象,然后返回到调用函数
}
void test03()
{
    Person p = doWork2();
}
int main()
{
    test01();
    test02();
    test03();
    system("pause");
    return 0;
}
构造函数调用规则

默认情况下,C++编译器至少给一个类添加3个函数

1、默认构造函数(无参,函数体为空)

2、默认析构函数(无参,函数体为空)

3、默认拷贝构造函数,对属性进行简单的值拷贝

构造函数调用规则如下:

  • 如果用户定义有参构造函数,C++不会再提供默认无参构造,但是提供默认拷贝构造
  • 如果用户定义拷贝构造函数,C++不会再提供其他构造函数

示例:

#include<iostream>
using namespace std;
//构造函数调用规则
class Person
{
public:
    Person()
    {
        cout << "person的默认构造函数调用" << endl;
    }
    ~Person()
    {
        cout << "person的析构函数调用" << endl;
    }
    Person(int age)
    {
        m_Age = age;
        cout << "person的有参函数调用" << endl;
    }
    /*Person(const Person& p)
    {
        m_Age = p.m_Age;
        cout << "person的拷贝函数调用" << endl;
    }*/

    int m_Age;
};
void test01()
{
    Person p1;
    p1.m_Age = 18;
    Person p2(p1);
    cout << "p2的年龄" << p2.m_Age<< endl;
}
void test02()
{
    //Person p; 如果用户定义有参构造函数,C++不会在提供默认无参构造
}

int main()
{
    test01();
    test02();
    system("pause");
    return 0;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。