C++编译链接那些事(二)
est(T a);
};
3.cpp:
[cpp]
#include
#include "2.h"
template
int A::test(T a)
{
std::cout<<"A test "<
return a;
}
1.cpp:
[cpp]
#include
#include "2.h"
void main()
{
A a;
a.test(4);
}
很遗憾的告诉你,链接出现问题:
[plain] view plaincopy
1.obj : error LNK2001: unresolved external symbol "public: int __thiscall A::test(int)" ( test@ $A@H@@QAEHH@Z)
找不到test的定义?怎么会呢?我们一般的类不都是这样写的么?注意这里是模版类,和一般类编译是不一样的。
分析:1.cpp中肯定是有test()的声明,寻找test()的定义是在链接的时候发生的。那可以肯定的是3.obj中肯定没有test()的定义<----这一切都是我们推出来的。那为什么没有test()的定义呢?
根据C++标准,当一个模板不被用到进它就不应该被具体化-----什么意思呢?
3.cpp里面如果没有用到A::test()的话,A
::test()函数的二进制代码就不会被编译到3.obj文件中去。
如果还是不明白的话,可以来实践一下:
3. cpp:
[cpp]
#include
#include "2.h"
template
int A::test(T a)
{