拷贝函数的四种调用时机
1、2:用一个对象去初始化另一个对象
#include<iostream>
using namespace std;
class test
{
public:
test()
{
m_a = 10;
}
test(int a, int b)
{
m_a = a;
m_b = b;
}
test(int a)
{
m_a = a;
m_b = 0;
}
test(const test& obj)//拷贝构造函数
{
m_a = obj.m_a+10;
m_b = obj.m_b;
cout << "我是拷贝构造函数" << endl;
}
public:
int getA()
{
return m_a;
}
int getB()
{
return m_b;
}
private:
int m_a;
int m_b;
};
void main()
{
test t1(2,3);
test t2(3,4);
test t3 = t1; //1、第一种拷贝构造函数的调用时机 用t1去初始化t3(调用拷贝构造函数)
test t4(t1); //2、第二种拷贝构造函数的调用时机
//t2 = t1; //用t1去给t2赋值,不是用t1去给t2初始化 赋值和初始化完全是两个不同的概念
cout <<"a1="<<t1.getA()<< endl;
cout << "a2=" << t2.getA() << endl;
cout << "a3=" << t3.getA() << endl;
cout << "a4="<<t4.getA()<< endl;
system("pause");
}
3、对象做函数参数
//第三种调用时机
#include<iostream>
using namespace std;
class test
{
public:
test()
{
}
test(int a, int b)
{
m_a = a;
m_b = b;
}
public:
int getA()
{
return m_a;
}
int getB()
{
return m_b;
}
private:
int m_a;
int m_b;
};
void f(test a)
{
cout << "m_a="<<a.getA()<< endl;
}
void root()
{
test t1(1,2);
test t2 = t1;
f(t2);//b实参取初始化形参a,会调用拷贝构造函数
cout << "m_b="<<t1.getB()<< endl;
}
void main()
{
root();
system("pause");
}
4、返回匿名对象
//第四种调用时机
#include<iostream>
using namespace std;
class test
{
public:
test()
{
}
test(int a, int b)
{
m_a = a;
m_b = b;
cout << "我是有参构造函数"<< endl;
}
test(const test& obj)
{
m_a = obj.m_a;
m_b = obj.m_b;
cout << "我是拷贝构造函数"<< endl;
}
~test()
{
cout << "我是一个析构函数"<< endl;
}
public:
int getA()
{
return m_a;
}
int getB()
{
return m_b;
}
private:
int m_a;
int m_b;
};
test g()
{
test A(1, 2); //调用有参构造函数
return A; //返回一个匿名对象
}
void objplay()
{
//若返回的匿名对象,来初始化另外一个同类型的对象
//那么匿名对象会直接转成新的对象
//test t2 = g(); //调用拷贝构造函数
//cout << t2.getA()<< endl;
//=若返回的匿名对象,赋值给另外一个同类型的对象
//,那么匿名对象会被析构
test t2;
t2 = g();
cout << t2.getA() << endl;
}
int main()
{
objplay();
system("pause");
}
本文详细解析了拷贝构造函数的四种调用时机,包括用一个对象初始化另一个对象、对象作为函数参数、返回匿名对象等场景,并通过具体代码示例进行说明。
1624

被折叠的 条评论
为什么被折叠?



