可能重复:
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行中的预处理器语句,该文件将编译但无法运行。
当我编译完文件后运行程序时,程序停止工作并弹出一个窗口,说程序“停止工作并且已关闭,问题导致应用程序停止正常工作.Windows会通知您是否一个解决方案是可用的“。为什么程序停止工作? – JDein 2012-03-06 05:47:24
@JDein:那不是“错误是什么”。这是“一些没有任何来自Windows的消息,每个应用程序中的每个错误都是相同的”。使用调试器和调试模式编译等,找出*错误是什么*。 – Puppy 2012-03-06 12:20:18
bug?你的意思是代码中有一些逻辑错误吗? – JDein 2012-03-07 06:04:09