C++ 构造函数与析构函数
1、什么是构造函数/析构函数:
首先,他们都是类的成员函数,名字和类名相同(析构在类名前加‘~’),没有返回值,没有void且可被重载。若用户未自定义,则编译器自动生成,其最大的特点就是类定义对象(或对象消亡)时自动运行的一个函数。
2、实例分析
#include <iostream>
using namespace std;
class A
{
public:
int a;
A();
A(int i);
~A();
};
A::A(void)
{
a = 5;
cout << "This is A" << endl;
}
A::A(int i)
{
a = i;
cout << "This is A" << endl;
}
A::~A()
{
cout << "This is ~A" << endl;
}
int main(void)
{
A c;
A D(100);
cout << "c: " << c.a << endl;
cout << "D: " << D.a << endl;
return 0;
}
运行打印的结果是:
This is A
This is A
c: 5
D: 100
This is ~A
This is ~A
--------------------------------
Process exited after 0.2047 seconds with return value 0
请按任意键继续. . .
由以上结果对应定义中的“类定义对象时自动执行”。
3、类继承时的的构造/析构函数
#include <iostream>
using namespace std;
class A
{
public:
int a;
A();
A(int i);
~A();
};
A::A(void)
{
a = 5;
cout << "This is A" << endl;
}
A::A(int i)
{
a = i;
cout << "This is A" << endl;
}
A::~A()
{
cout << "This is ~A" << endl;
}
class B : public A
{
public:
char c;
B();
B(char i);
~B();
};
B::B(void)
{
c = 'a';
cout << "this is b2" << endl;
}
B::B(char i)
{
c = i;
cout << "this is b1" << endl;
}
B::~B()
{
cout << "this is ~B" << endl;
}
int main(void)
{
/**********************
A c;
A D(100);
cout << "c: " << c.a << endl;
cout << "D: " << D.a << endl;
****************************/
B c;
B d('z');
cout << "c: " << c.c << endl;
cout << "d: " << d.c << endl;
return 0;
}
其结果为:
This is A
this is b2
This is A
this is b1
c: a
d: z
this is ~B
This is ~A
this is ~B
This is ~A
--------------------------------
Process exited after 0.3514 seconds with return value 0
请按任意键继续. . .
由以上结果可以知道,基类的构造函数先被执行,析构函数后被执行(这是重点,面/笔试中经常有)。
版权声明:本文为Pompey_Wang原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。