C++ 拷贝构造函数在下面三种情况下调用:
(1)使用一个已经创建的对象来初始化一个对象
(2)用值传递的方式给函数参数传值
(3)值方式返回局部对象
(1)使用一个已经创建的对象来初始化一个对象
#include "iostream"
using namespace std;
class Person
{
public:
Person()
{
cout << "默认构造函数" << endl;
}
Person(int age)
{
m_Age = age;
cout << "有参构造函数" << endl;
}
Person(const Person & p)
{
cout << "拷贝构造函数" << endl;
m_Age = p.m_Age;
}
~Person()
{
cout << "调用析构函数" << endl;
}
int m_Age;
};
void test1()
{
Person p1(100);
Person p2(p1);
cout << "p2的年龄:"<<p2.m_Age<<endl;
}
int main()
{
test1();
return 0;
}
(2)用值传递的方式给函数参数传值
#include "iostream"
using namespace std;
class Person
{
public:
Person()
{
cout << "默认构造函数" << endl;
}
Person(int age)
{
m_Age = age;
cout << "有参构造函数" << endl;
}
Person(const Person & p)
{
cout << "拷贝构造函数" << endl;
m_Age = p.m_Age;
}
~Person()
{
cout << "调用析构函数" << endl;
}
int m_Age;
};
void test(Person p)
{
}
void test1()
{
Person p;
test(p);
}
int main()
{
test1();
return 0;
}
(3)值方式返回局部对象
#include "iostream"
using namespace std;
class Person
{
public:
Person()
{
cout << "默认构造函数" << endl;
}
Person(int age)
{
m_Age = age;
cout << "有参构造函数" << endl;
}
Person(const Person & p)
{
cout << "拷贝构造函数" << endl;
m_Age = p.m_Age;
}
~Person()
{
cout << "调用析构函数" << endl;
}
int m_Age;
};
Person test()
{
Person p1;
return p1;
}
void test1()
{
Person p = test();
}
int main()
{
test1();
return 0;
}