拷贝构造函数的调用时机:
1.用一个已经创好的对象来初始化一个新对象
2.用值传递来给形参传值的时候
3.以值传递的方式返回局部对象都是利用拷贝构造函数的形式
分别用三个测试案例来举例
#include<iostream>
using namespace std;
class person
{public:
person()
{
}
person(int a)
{
m_age = a;
}
~person()
{
}
person(const person& p)
{
m_age = p.m_age;
cout << "拷贝构造函数的应用" << endl;
}
int m_age;
};
void test01()
{
person p1(10);
person p2(p1);
cout << "p2 的年龄为" << p2.m_age << endl;
}
void dowork(person p)
{
cout << "今天天气真好" << endl;
}
void test02()
{
person p;
dowork(p);
}
person test03()
{
person p;
cout << "person p的地址为" << &p << endl;
return p;
}
void test04()
{
person p5=test03();
cout << "person p5的地址为" << &p5 << endl;
}
int main(void)
{
test01();
cout << endl;
test02();
cout << endl;
test04();
cout << endl;
system("pause");
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)