【问题标题】:Problem working with template and Inheritance, Error Undefined symbols for architecture x86_64:使用模板和继承时出现问题,架构 x86_64 的错误未定义符号:
【发布时间】:2020-11-16 21:38:04
【问题描述】:

我在尝试构建我的项目时遇到了这个问题,我的函数有 6 个未定义符号错误:

显示最近的问题 未定义符号:Hashint::deleteHash(int)

未定义符号:Hashint::insertHash(int)

未定义符号:Hashint::searchHash(int)

未定义符号:Hashint::print()

未定义符号:HashTable::HashTable(int)

未定义符号:Hashint 的 vtable

我有一个带有内部类(Item)的模板类:

template <class T, class K>
class HashTable
 
{
public:
    enum state {empty, full, deleted};
    class Item
    {
    public:
        T data;
        K key;
        state flag;
        Item(){}
        Item(T d, K k, state f){ data=d; key=k; flag=f;}
        
    };

    
public:
    Item* table;
    int size;
    
    HashTable(int sizeHash);

    virtual ~HashTable() {}
    
    virtual int h1(K k);
    virtual int h2(K k);
    
    //returns the index of the hashing table for the key k at the try number i
     virtual int hash(K k, int i);
     virtual int searchHash(K k); // searches and return the index
    virtual  int insertHash(K k); // insert
    virtual void deleteHash(K k); // delete
     virtual void print();
};

我的类 Hashint 继承自哈希表:

class Hashint : public HashTable<int,int>  {
   
public:
    int sizeTable;
    Item* table;
    
    
    Hashint(int size):HashTable<int, int>(size)
    {
        table= new Item [size];
        sizeTable = size;
        for (int i=0; i<sizeTable; i++)
            table[i].flag = empty;
    }
        
    int h1(int k);
    int h2(int k);
    int hash(int k, int i);
    int searchHash(int k);
    int insertHash(int k);
    void deleteHash(int k); 
    void print();    
};

我还有一个 Hashtable 类的 cpp 文件,但是如果我发布它会太长...

我不明白是什么问题,我做错了继承?或者问题出在模板上? 如果你能帮助我,我会非常高兴! 谢谢你!!

【问题讨论】:

  • 确保您在标头而不是 .cpp 文件中实现了 HashTable 模板。在 cpp 文件中实现它会导致这种类型的错误。
  • 我更改了它,我将所有内容都放在了 .h 文件中,但它仍然无法正常工作...它显示与未定义符号相同的错误

标签: c++ templates inheritance polymorphism hashtable


【解决方案1】:

必须在实例化模板类之前定义模板类中的函数。将函数定义添加到头文件中,它应该可以工作。

例如检查此代码:

// class templates
#include <iostream>
using namespace std;

template <class T>
class mypair {
T a, b;
public:
mypair (T first, T second)
  {a=first; b=second;}
T getmax ();
};

template <class T>
T mypair<T>::getmax ()
{
T retval;
retval = a>b? a : b;
return retval;
}

int main () {
mypair <int> myobject (100, 75);
cout << myobject.getmax();
return 0;
}

getMax 在用于主代码之前已经在类之外定义

Found this code in this link

【讨论】:

    猜你喜欢
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 2018-07-21
    • 1970-01-01
    • 2016-02-02
    • 2017-02-15
    • 1970-01-01
    相关资源
    最近更新 更多