我有一些代码:
file.h:
#ifndef SAKE_H_INCLUDED
#define SAKE_H_INCLUDED
template <class T>
void swapq(T& a, T& b);
#endif // SAKE_H_INCLUDED
file.cpp:
#include "file.h"
template <class T>
void swapq(T& a, T& b){
T temp=a;
a=b;
b=temp;
}
main.cpp:
#include <iostream>
#include "file.h"
using namespace std;
int main()
{
int a=3, b=2;
swapq(a,b);
cout<<a<<" "<<b<<endl;
return 0;
}
因此,当我构建它时,编译器会向我显示错误:
||=== Build: Release in test (compiler: GNU GCC Compiler) ===|
obj/Release/main.o||In function `main':|
main.cpp:(.text.startup+0x2d)||undefined reference to `void
swapq<int>(int&, int&)'|
||error: ld returned 1 exit status|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0
second(s)) ===|
我删除了“ template”并将void函数中的“ T”替换为“ int”,并且构建成功。如何在“ file.h”和“ file.cpp”中使用模板,以便可以交换具有不同数据类型的两个变量?