2012-03-05 48 views
0

可能重复:
Why can templates only be implemented in the header file?编译器会引发错误说 “翻译字典<int>一个(10)” 具有初始值设定,但不完全的类型”

classdeclaration.h

template<typename anytype> 
class List; 

template<typename anytype> 
class Dict; 

classdefinition.cpp

#include "classdeclaration.h" 
#include<iostream> 

using std::cout; 
using std::endl; 

template<typename anytype> 
class List{ 
    private: 
     int size; 
     anytype * list; 
    public: 
     List(int a); 
     List(const List<anytype> &a); 
     int getSize(); 
     ~List(); 
}; 

template<typename anytype> 
List<anytype>::List(int a){ 
      size=a; 
      list=new anytype[size]; 
      cout<<"List object initialized. The address of list is "<<list<<endl; 
     } 

template<typename anytype> 
int List<anytype>::getSize(){ 
     return size; 
     } 

template<typename anytype> 
List<anytype>::List(const List<anytype> &a){ 
     this.size=a.getSize(); 
     this.list=new List<anytype>(size); 
     } 

template<typename anytype> 
List<anytype>::~List(){ 
      delete[] list; 
      cout<<"List destructor called."<<endl; 

} 


template<typename anytype> 
class Dict{ 
    private: 
     int dicta; 
     List<anytype> *dict; 
    public: 
     Dict(int num); 
     Dict(const Dict<anytype>& a); 
     int getDicta(); 
     ~Dict(); 
}; 

template<typename anytype> 
Dict<anytype>::Dict(int num){ 
      dicta=num; 
      dict=new List<anytype>(dicta); 
      cout<<"Dict object initialized. The address of dict is "<<dict<<endl; 
     } 

template<typename anytype> 
int Dict<anytype>::getDicta(){ 
      return dicta; 
     } 

template<typename anytype> 
Dict<anytype>::Dict(const Dict<anytype> & a){ 
      this.dicta=a.getDicta; 
      dict=new Dict<anytype>(dicta); 
     } 

template<typename anytype> 
Dict<anytype>::~Dict(){ 
      delete[] dict; 
      cout<<"Dict destructor called."<<endl; 
     } 

TEST.CPP

#include<iostream> 
#include "classdeclaration.h" //A 


int main() 
{ 
    using namespace std; 
    Dict<int> a(10); 
    cout<<"The address of Dict<int> a is "<<&a<<endl; 
} 

这里的问题是,该文件将不会使用命令编译 “G ++ TEST.CPP classdefinition.cpp -oe:\ KC” 和编译器会抛出一个错误,说Dict<int> a(10)有初始值设定项,但是不完整的类型。不完整类型是什么意思,我该如何解决?

另一个问题是,如果我用#include“classdefinition.cpp”替换A行中的预处理器语句,该文件将编译但无法运行。

回答

3

您必须将所有模板的定义放在头文件中。与常规函数不同,编译器无法找到翻译单元之间的定义。

另外,如果你不告诉我错误是什么,我该如何知道为什么你的代码将无法运行?

+0

当我编译完文件后运行程序时,程序停止工作并弹出一个窗口,说程序“停止工作并且已关闭,问题导致应用程序停止正常工作.Windows会通知您是否一个解决方案是可用的“。为什么程序停止工作? – JDein 2012-03-06 05:47:24

+0

@JDein:那不是“错误是什么”。这是“一些没有任何来自Windows的消息,每个应用程序中的每个错误都是相同的”。使用调试器和调试模式编译等,找出*错误是什么*。 – Puppy 2012-03-06 12:20:18

+0

bug?你的意思是代码中有一些逻辑错误吗? – JDein 2012-03-07 06:04:09

1

您应该始终将完整的类定义放在头文件中,否则您将总是得到类似的错误。

当涉及到模板,完整的实现也需要使用该类的代码看到。这是因为模板类没有完全声明,除非实际使用模板参数。

+0

感谢您的建议,PileBorg。在将“classdefinition.cpp”与“classdelcaration.h”组合起来之后,该文件将被编译。但是当我运行该程序时,它停止工作,并弹出一个窗口,声明程序“停止工作并关闭了。” 问题导致应用程序无法正常工作。如果解决方案可用,Windows会通知您。我的代码有问题吗? – JDein 2012-03-06 05:39:21

相关问题