1.拷贝构造函数
拷贝构造函数的调用时机
class A
{
public:
//默认构造函数
A()
{
m_Hp = 100;
cout << "A默认构造函数调用完毕" << endl;
}
//有参构造函数
A(int hp)
{
m_Hp = hp;
cout << "A有参构造函数调用完毕" << endl;
}
A(const A& a)
{
m_Hp = a.m_Hp;
cout << "A拷贝构造函数调用完毕" << endl;
}
~A()
{
cout << "A析构函数调用完毕" << endl;
}
private:
int m_Hp;
};
1.用已经创建过的对象来初始化对象
void func1()
{
cout << "---------func1----------" << endl;
A a1(10);
A a2(a1);
}
2.函数的传参
A a = a1;等效于A a(a1);
void test(A a)
{
}
void func2()
{
cout << "---------func2----------" << endl;
A a1;
test(a1);
}
3.函数的返回值
A test3()
{
A a(40);
return a;
}
void func3()
{
cout << "---------func3----------" << endl;
A a = test3();
}
2.初始化列表
class Hero
{
public:
Hero(string name,int hp):m_Name(name),m_Hp(hp){}
void Print(){
cout << "英雄:" << m_Name << "的血量是" << m_Hp << endl;
}
private:
string m_Name;
int m_Hp;
};
int main()
{
Hero h("李白", 100);
h.Print();
}