构造和析构

构造和析构

构造函数

定义

C++中的类可以定义与类名相同的特殊成员函数,这种与类名相同的成员函数叫做构造函数.

1
2
3
4
5
6
7
class 类名
{
类名(形式参数)
{
构造体
}
}
1
2
3
4
5
6
class A
{
A(形参)
{
}
}

调用

自动调用:一般情况下C++编译器会自动调用构造函数.
手动调用:在一些情况下则需要手工调用构造函数.

规则:

1 在对象创建时自动调用,完成初始化相关工作。
2 无返回值,与类名同,默认无参,可以重载,可默认参数。
3 一经实现,默认不复存在。

析构函数

定义

C++中的类可以定义一个特殊的成员函数清理对象,这个特殊的成员函数叫做析构函数.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class 类名
{
~类名()
{
析构体
}
}

//--------------------------------------------

class A
{
~A()
{

}
}

规则:

1 对象销毁时,自动调用。完成销毁的善后工作。
2 无返值 ,与类名同。无参。不可以重载与默认参数

析构函数的作用,并不是删除对象,而在对象销毁前完成的一些清理工作。

test.h

1
2
3
4
5
6
7
8
9
10
11
12
13
#pragma once
class test
{
public:
test();
test(int a,int b);
test(int a);
~test();
void print();
private:
int mA;
int mB;
};

test.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include "test.h"
#include<iostream>

using namespace std;
test::test()
{
mA = 0;
mB = 0;
}

test::test(int a, int b)
{
mA = a;
mB = b;
}

test::test(int a)
{
mA = a;
mB = 0;
}


test::~test()
{
cout << "~test" << endl;
}

void test::print()
{
cout << mA << endl;
cout << mB << endl;

}

main.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<iostream>
#include"test.h"
using namespace std;

int main(int argc, char* argv[])
{
test t1(100, 200);
test t2(111);

t1.print();
t2.print();
return 0;
}