拷贝构造
#include <iostream>
using namespace std;
class Monster
{
public:
Monster();
Monster(char * name,int hp,float speed);
~Monster();
Monster(Monster &obj);
Monster(Monster &obj1, int val);
public:
string m_name;
int m_hp;
float m_speed;
};
Monster::Monster()
{
m_name="name";
m_hp=100;
m_speed=10.0f;
cout << "无参构造" << endl;
};
Monster::Monster(char * name,int hp,float speed)
{
m_name=name;
m_hp=hp;
m_speed=speed;
cout << "带参构造" << endl;
};
Monster::~Monster()
{
cout << "析构函数" << endl;
}
// 拷贝构造
Monster::Monster(Monster &obj)
{
m_name = obj.m_name;
m_hp = obj.m_hp;
m_speed = obj.m_speed;
cout << "拷贝构造1" << endl;
};
Monster::Monster(Monster &obj, int val){
m_name = obj.m_name;
m_hp =val;
m_speed = obj.m_speed;
cout << "拷贝构造2" << endl;
};
void test_func_2(Monster monster){}
Monster test_func_1(){
Monster l1;
l1.m_hp=20;
l1.m_speed=10.0f;
return l1;
}
int main()
{
Monster m0;
m0=test_func_1();
//test_func_2(m0);
//Monster m1("皮卡丘", 10,1.0f);
//test_func_1(m0);
//Monster m3 = m0; //同类对象初始化
//Monster m3(m0); // 使用一个对象构造另一个对象
// Monster *p = new Monster;
// delete p;
// p=nullptr;
}
拷贝构造函数调用:
1、使用一个已经创建完毕的对象来初始化一个新对象
2、值传递的方式给函数参数传值
3、 值方式返回局部对象
浙公网安备 33010602011771号