c++ 基础知识-类和对象-对象特性-构造函数和析构函数
1.构造函数和析构函数初始化及分类
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
Person()
{
m_age = 2;
cout<<"Person:默认构造函数"<<endl;
}
Person(int a)
{
m_age = a;
cout<<"Person:有参数构造函数"<<endl;
}
Person(Person &p)
{
m_age = p.m_age;
cout<<"Person:拷贝构造函数"<<endl;
}
~Person()
{
cout<<"age :"<<m_age<<"Person:析构函数"<<endl;
}
private:
int m_age;
};
void fun()
{
Person p4;
cout<<"默认构造函数结束"<<endl;
Person p5 = Person(5);
cout<<"有参数构造函数结束"<<endl;
Person p6 = Person(p5);
cout<<"拷贝构造函数结束"<<endl;
Person(10);
cout<<"匿名对象结束"<<endl;
}
int main()
{
fun();
return 0;
}
3.拷贝构造函数调用时机
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
Person()
{
m_age = 2;
cout<<"Person:默认构造函数"<<endl;
}
Person(int a)
{
m_age = a;
cout<<"Person:有参数构造函数"<<endl;
}
Person(const Person &p)
{
m_age = p.m_age;
cout<<"Person:拷贝构造函数"<<endl;
}
~Person()
{
cout<<"age :"<<m_age<<" Person:析构函数"<<endl;
}
private:
int m_age;
};
void fun()
{
Person p1(20);
Person p2(p1);
}
void fun01(Person p)
{
}
Person fun02()
{
Person p1;
cout<<"fun02 : Person p1"<<endl;
return p1;
}
int main()
{
fun02();
return 0;
}
|