从c++中的模板类继承,编译失败

  • 本文关键字:继承 编译 失败 c++ c++
  • 更新时间 :
  • 英文 :


我的问题是,我有一个模板类template<class T> AList作为基础,我想从模板中得到一个派生类,即得到class BList: public AList<mydefinedtype>没有太多的修改。

alist.h

#ifndef alist_h
#define alist_h
template<class T> class AList
{
public:
AList(){
arr = new T[20];
numitems = 0;
};
void append(T value);

private:
T *arr;
int numitems;
};

#endif /* alist_h */

alist.cpp

#include "alist.h"
template<class T> void AList<T>::append(T value)
{
arr[numitems] = value;
++numitems;
return;
}

blist.h

#include "alist.cpp"
#include <string>
using namespace std;
typedef struct 
{
string a, b;
int key;
} record;
class BList: public AList<record>{
public:
void test(void){
cout << "this is from BList" << endl;
}
};

blist.cpp

#include "blist.h"

main.cpp

#include <iostream>
#include "blist.cpp"
using namespace std;

int main(){
record testRecord[3];
testRecord[0] = {"Mark", "A", 1};
testRecord[1] = {"Anla", "B", 2};
testRecord[2] = {"Cindy", "C", 3};
BList blist = BList();
for(auto i: testRecord){
// blist.append(i); // will compile error
blist.test();
} 
return 0;
}

它将失败如下,我想知道如何编译或如何修复这个错误。错误信息

Undefined symbols for architecture x86_64:
"AList<record>::append(s)", referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64

不确定问题从何而来

// Example program
#include <iostream>
#include <string>

struct record{
int a;
};

template<class T> 
class AList{
public:
AList()=default;
void append(T value){}
};

template<class T>
class BList:public AList<T>{
public:
void test(void){}
};


int main()
{
BList<record> blist;

record recordarr[3] ;
// some initialization 

for(auto i:recordarr){
blist.append(i); 
blist.test(); 
}
}

问题在于,list()构造函数、append(T)和test()只声明了,没有定义。以上代码应该可以编译。

你应该把你的模板类全部放在头文件中。有关原因的详细信息,请参阅此问题和c++常见问题解答。

你也不应该#include.cpp文件。你应该只使用#include头文件。

下面我有你的代码后,需要修改,使其编译。我还删除了你的内存泄漏。

alist.h:

#ifndef alist_h
#define alist_h
template<class T> class AList {
public:
AList() {
arr = new T[20];
numitems = 0;
};
~AList() {
delete[] arr;
}
void append(T value) {
arr[numitems] = value;
++numitems;
}
private:
T *arr;
int numitems;
};
#endif /* alist_h */

blist.h:

#ifndef blist_h
#define blist_h
#include "alist.h"
#include <string>
using namespace std;
typedef struct {
string a, b;
int key;
} record;
class BList: public AList<record> {
public:
void test(void) {
cout << "this is from BList" << endl;
}
};
#endif /* blist_h */

main.cpp:

#include <iostream>
#include "blist.h"
using namespace std;
int main() {
record testRecord[3];
testRecord[0] = {"Mark", "A", 1};
testRecord[1] = {"Anla", "B", 2};
testRecord[2] = {"Cindy", "C", 3};
BList blist = BList();
for (auto i: testRecord) {
blist.append(i);
blist.test();
}
return 0;
}

变更汇总

我做了以下修改:

  • AList::append的body移至alist.h,并删除alist.cpp
  • 添加AList析构函数来释放AList::AList中分配的动态内存
  • blist.h中,包含alist.h而不是alist.cpp
  • 删除blist.cpp
  • main.cpp中,包含blist.h而不是blist.cpp

最新更新