|
刚学模板编程,有一个简单的程序,三个文件main.cpp,tt.h,tt.cpp
//main.cpp
#include <iostream>
#include "tt.h"
int main()
{
A<int> a;
a.test(10);
return 0;
}
//tt.h
#ifndef TT_H
#define TT_H
template<typename T>
class A{
public:
void test(T val);
};
#include "tt.cpp"
#endif
//tt.cpp
template<typename T>
void A<T>::test(T val)
{
std::cout << val << std::endl;
}
编译错误:
1>e:\testtemp\testtemp\tt.cpp(4) : error C2143: 语法错误 : 缺少“;”(在“<”的前面)
1>e:\testtemp\testtemp\tt.cpp(4) : error C2182: “A”: 非法使用“void”类型
1>e:\testtemp\testtemp\tt.cpp(4) : error C2988: 不可识别的模板声明/定义
1>e:\testtemp\testtemp\tt.cpp(4) : error C2059: 语法错误 : “<”
1>e:\testtemp\testtemp\tt.cpp(4) : error C2039: “test”: 不是“`global namespace'”的成员
模板类需要看到类成员函数的定义,所以我把定义放在.h文件中,编译连接是通过的。
如果我把main.cpp中的#include 改为"tt.cpp",然后在tt.cpp中包含tt.h,编译连接也是通过的。
但是我使用了c++ primer中写的这个包含编译模型,却始终通不过编译。我想不明白的是,为什么tt.h中包含了tt.cpp的实现,为什么却有错呢。求高手给解释下,还有该怎么改。
我用的是VS2005。
|
|