类模板的多文件编写

类模板的多文件编写

不建议类模板分多文件编写

如果多文件编写类模板,在调用实例化模板类要包含cpp实现

一般的类模板实现文件后缀名是hpp

1624058903726

如果不包含类实现,在调用具体化模板类时,因为编译器是逐个文件进行编译的,所以编译器在当前文件找不到类实现,会认为类实现在其他文件,然后编译器会自动跳过,交给链接器处理,而链接器又找不到具体化函数,就会报错

h头文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>

using namespace std;


template <class T>
class Complex
{
public:
Complex();
~Complex();
Complex(T a, T b);
void pirntComplex();

Complex operator+(Complex &another);

Complex operator-(Complex &another);
private:
T a;
T b;
};

hpp文件

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include "Complext.h"

//最终通过第二次编译生成class Complex<int> 是在cpp文件中展开
/*
class Complex<int>
{
}
*/

template<class T>
Complex<T>::Complex()
{
this->a = 0;
this->b = 0;
}

template<class T>
Complex<T>::~Complex()
{
}

template<class T>
Complex<T>::Complex(T a, T b)
{
this->a = a;
this->b = b;
}

template<class T>
void Complex<T>::pirntComplex()
{
cout << "a = " << a << "b = " << b << endl;
}

template<class T>
Complex<T> Complex<T>::operator+(Complex<T> &another)
{
Complex temp(this->a + another.a, this->b + another.b);
return temp;
}


template<class T>
Complex<T> Complex<T>::operator-(Complex<T> &another)
{
Complex temp(this->a - another.a, this->b - another.b);
return temp;
}
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
#define  _CRT_SECURE_NO_WARNINGS 
#include <iostream>
#include "Complext.h"
#include "Complext.hpp" //不能够引入cpp
#include <vector>

//模板类的 方法的实现不能够用多文件编写。
//如果实现多文件的 由于二次编译 真正的实现体是在cpp文件定义的。需要引入cpp头文件。

using namespace std;



int main(void)
{

Complex<int> c1(10, 20);
c1.pirntComplex();

Complex<int> c2(1, 2);

Complex<int> c3; //调用无参构造
c3 = c1 + c2;

c3.pirntComplex();

return 0;
}