C++中模板的编译与文件部署问题

来源:百度知道 编辑:UC知道 时间:2024/06/06 16:48:44
假设现在有一个主函数,调用一个函数模板compare。我把这个程序写在三个文件里:
---------------------------------------------------
MAIN.CPP:
#include <iostream>
#include "func.h"
using namespace std;
void main() {
int a = 5, b = 4;
cout << compare(a,b) << endl;
getchar();
}
---------------------------------------------------
FUNC.H: (包含compare函数的声明)
#ifndef FUNC_H
#define FUNC_H
template <class T, class U>
int compare(const T& a, const U& b);
#endif
---------------------------------------------------
FUNC.CPP (包含compare函数的定义)
#include "func.h"
template <class T, class U>
int compare(const T& a, const U& b) {
if (a<b) return -1;
if (b<a) return 1;
return 0;
}
---------------------------------------------------
编译的时候出现连接错误,说是找不到compare的定义。书上说在编译函数模板的时候,需要知道函数模板的定义,只知道声明不行,这一点与非模板函数不同。我想问一下:
1. 为什么编译函数模板时需要知道其定义?
2.

模板这玩意不在当前编译单元(也就是cpp)里使用就不会被编译(想编译也编译不了,起码不完整) 所以一般要么写在和调用同一个cpp里,要么完全写在.h里(不是把声明写.h里把定义写在.cpp里,直接把定义写在.h里)

模板不会产生定义重复问题。 (指链接的时候... 你怎么搞出重复定义的我还真想不出来...)

第三个问题没看明白bbb

--

#include的功能...就是把一个文件的内容直接粘贴到当前文件...

比如是
a.cpp
1
#include "b.h"
2

b.h
3

与处理后就会有a.i
1
#line 1 "b.h"
3
#line 3 "a.cpp"
2
这种结果,只是把b.h的内容插入了#include "b.h"的位置。那两个#line不用管,是为了正确返回错误出现位置用的。

--

模板必须有定义因为必须在使用的时候补完。你不使用根本没办法编译模板。

比如你在a.cpp里写了一个模板,b.cpp里使用这个模板。a.cpp里并没有使用模板所以根本没有编译(模板只有使用的时候才能提供编译需要的参数)。b.cpp里使用的话,根本链接不到相应的代码。

---------------------------------------------------
MAIN.CPP:
#include <iostream>
#include "func.h"
using namespace std;
void main() {
int a = 5, b = 4;
cout << compare(a,b) << endl;
getchar();
}