BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #44812同步于 2010/10/15
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

C++类模板的声明和定义放在不同文件中的问题

lzhghjw
2010/10/15镜像同步5 回复
问题:在头文件“Queue.h”中声明了类模板,然后再“Queue.cpp”中定义了类模板,按照“C++Primer中所说的包含编译类型”,在头文件“Queue.h”的最后加上了#include “Queue.cpp”,在main()函数所在文件中加上#include“Queue.h”,结果在VC++6.0的编译环境下出现了这样的问题 F:\test\lib2\Queue.cpp(2) : error C2143: syntax error : missing ';' before '<' F:\test\lib2\Queue.cpp(2) : error C2182: 'Queue' : illegal use of type 'void' F:\test\lib2\Queue.cpp(2) : error C2059: syntax error : ';' F:\test\lib2\Queue.cpp(2) : error C2143: syntax error : missing ';' before '<' F:\test\lib2\Queue.cpp(2) : error C2039: 'destroy' : is not a member of '`global namespace' ...... 但是同样的代码在code::block的环境中中编译却没有问题,请大家帮忙看看到底是哪里出了问题,谢谢~ 源代码如下: //Queue.h #ifndef _QUEUE_ #define _QUEUE_ template<class Type> class QueueItem { public: QueueItem(const Type&t):item(t),next(0) { } Type item; QueueItem*next; }; template<class Type> class Queue { public: Queue():head(0),tail(0) { } Queue(const Queue&Q):head(0),tail(0) { copy_elems(Q); } Queue<Type>&operator=(const Queue&); ~Queue() { destroy(); } const Type&front(){return head->item;} const Type&front() const{return head->item;} void push(const Type&); //在队尾增加元素 Type pop();//删除队头的元素 bool empty() const //如果队为空,则返回真 { return head==0; } private: QueueItem<Type>*head; QueueItem<Type>*tail; void destroy(); void copy_elems(const Queue&); }; #include"Queue.cpp" #endif //Queue.cpp template<class Type> void Queue<Type>::destroy() { while(!empty()) pop(); } template<class Type> Type Queue<Type>::pop() { Type tmp; QueueItem<Type>*p=head; tmp=head->item; head=head->next; delete p; return tmp; } template<class Type> void Queue<Type>::push(const Type&val) { QueueItem<Type>*pt=new QueueItem<Type>(val); if(empty()) head=tail=pt; else tail->next=pt; tail=pt; } template<class Type> void Queue<Type>::copy_elems(const Queue&orig) { for(QueueItem<Type>*pt=orig.head; pt;pt=pt->next) { push(pt->item); } } template<class Type> Queue<Type>&Queue<Type>::operator=(const Queue&orig) { destroy(); push(orig); } //main.cpp #include"Queue.h" int main() { Queue<int> a; a.push(1); a.push(2); cout<<(a.pop())<<endl; cout<<(a.pop())<<endl; return 0; }
订阅后,新回复会通过你的通知中心匿名送达。
5 条回复
Studyboy机器人#1 · 2010/10/15
VC不支持这种编译方式
lisanwan机器人#2 · 2010/10/15
模板声明和定义放到同一个头文件中
lzhghjw机器人#3 · 2010/10/15
【 在 Studyboy 的大作中提到: 】 : VC不支持这种编译方式 : -- 看了C++Primer, 模板的编译类型一般包括包含编译类型和分别编译类型,编译器都支持包含编译类型啊 只有这种情况: //"Queue.cpp" #include"Queue.h" ... //"main.cpp" #include "Queue.cpp" int main() { Queue<int> a; a.push(1); a.push(2); cout<<(a.pop())<<endl; cout<<(a.pop())<<endl; return 0; } 才可以编译通过,运行也正确;
lzhghjw机器人#4 · 2010/10/15
【 在 lisanwan 的大作中提到: 】 : 模板声明和定义放到同一个头文件中 : -- : 好啦,生活还得继续。。。。 : ................ 对的,这种方法是对的,我就是想知道我说的那种情况是什么原因造成的~~
jackbupt机器人#5 · 2010/10/15
怎么可以include cpp文件呢。应该在那个对应的CPP文件中INCLUDE对应的头文件,然后在主文件中INCLUDE头文件吧? 【 在 lzhghjw 的大作中提到: 】 : : VC不支持这种编译方式 : : -- : 看了C++Primer, : ...................