构造函数和析构函数
#include<iostream>
using namespace std;
class MYclass
{
public:
MYclass()
{
cout << "MYclass的构造函数调用" << endl;
}
~MYclass()
{
cout << "MYclass的析构函数调用" << endl;
}
};
void test01()
{
MYclass c;
}
int main()
{
test01();
system("pause");
return 0;
}
构造函数的分类与调用
#include<iostream>
using namespace std;
class Persion
{
public:
Persion()
{
cout << "Persion的无参函数调用" << endl;
}
Persion(int age)
{
m_age = age;
cout << "Persion的有参函数调用" << endl;
}
int m_age;
Persion(const Persion &p)
{
m_age = p.m_age;
cout << "Persion的拷贝函数调用" << endl;
}
~Persion()
{
cout << "Persion的析构函数调用" << endl;
}
};
void test01()
{
Persion p;
Persion p2(10);
Persion p3(p2);
Persion p4 = Persion(10);
Persion P5 = Persion(p4);
Persion p();
Persion(10);
Persion(p5);
Persion p6 = 10;
Persion p7 = p6;
}
int main()
{
test01();
system("pause");
return 0;
}
拷贝构造函数的调用时机
#include<iostream>
using namespace std;
class Persion
{
public:
Persion()
{
cout << "无参构造函数调用" << endl;
}
Persion(int age)
{
m_age = age;
cout << "有参构造函数调用" << endl;
}
Persion(const Persion &p)
{
cout << "拷贝构造函数调用" << endl;
m_age = p.m_age;
}
~Persion()
{
cout << "析构函数调用" << endl;
}
int m_age;
};
void test01()
{
Persion p1(18);
Persion p2(p1);
cout << "p2的年龄为:" << p2.m_age << endl;
}
void f(Persion p)
{
;
}
void test02()
{
Persion p1;
f(p1);
}
Persion f2()
{
Persion p1;
return p1;
}
void test03()
{
Persion p1 = f2();
}
int main()
{
test03();
system("pause");
return 0;
}
构造函数的调用规则
#include<iostream>
using namespace std;
class Persion
{
public:
Persion(int age)
{
m_age = age;
cout << "有参构造函数调用" << endl;
}
~Persion()
{
cout << "析构函数调用" << endl;
}
int m_age;
};
void test01()
{
Persion p1(10);
Persion P2(p1);
cout << "p2.age = " << P2.m_age << endl;
}
void test02()
{
Persion p1(18);
Persion p2(p1);
cout << "p2.age = " << p2.m_age << endl;
}
void test03()
{
}
int main()
{
test02();
system("pause");
return 0;
}