【问题标题】:Undefined reference to template class destructor [duplicate]对模板类析构函数的未定义引用[重复]
【发布时间】:2015-10-12 18:58:49
【问题描述】:

我的模板类队列有问题,我一直在实现文件中实现功能,所以我看到this 的答案并决定在头文件中进行实现:

队列.hpp

#ifndef QUEUE_HPP
#define QUEUE_HPP

#include "Instruction.hpp"
#include  "MicroblazeInstruction.hpp"

#include <memory>
#include <list>

template<typename T>
class Queue{
public:
    Queue(unsigned int max): maxSize{max} {};
    ~Queue();

    std::list<T> getQueue(){
        return queue;
    };

    void push(T obj){
        if(queue.size() < maxSize){
            queue.push_front(obj);
        }
        else{
            queue.pop_back();
            queue.push_front(obj);
        }
    };

private:
    Queue(const Queue&);
    Queue& operator=(const Queue&);
    unsigned int maxSize;
    std::list<T> queue;
};


#endif

我从我的 main 调用这个函数:

#include "icm/icmCpuManager.hpp"
#include "Instruction.hpp"
#include "MicroblazeInstruction.hpp"
#include "CpuManager.hpp"
#include "File.hpp"
#include "Utils.hpp"
#include "MbInstructionDecode.hpp"
#include "Queue.hpp"
#include "PatternDetector.hpp"

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <sstream>
#include <cstdint>
#include <memory>

int main(int argc, char *argv[]){
    ...

    // Create pointer to microblaze instruction
    std::shared_ptr<MicroblazeInstruction> newMbInstruction;

    // Maximum pattern size
    const unsigned int maxPatternSize = 300;

    // Creating the Queue
    Queue<std::shared_ptr<MicroblazeInstruction>> matchingQueue(maxPatternSize);    

    ...
}

我仍然有这个编译错误:

# Linking Platform faith.exe
g++ ./CpuManager.o ./Instruction.o ./File.o ./Utils.o ./MicroblazeInstruction.o ./MbInstructionDecode.o ./PatternDetector.o ./main.o -m32 -LC:\Imperas/bin/Windows32 -lRuntimeLoader -o faith.exe
./main.o:main.cpp:(.text.startup+0x552): undefined reference to `Queue<std::shared_ptr<MicroblazeInstruction> >::~Queue()'
./main.o:main.cpp:(.text.startup+0x83a): undefined reference to `Queue<std::shared_ptr<MicroblazeInstruction> >::~Queue()'
c:/mingw/mingw32/bin/../lib/gcc/i686-w64-mingw32/4.7.0/../../../../i686-w64-mingw32/bin/ld.exe: ./main.o: bad reloc address 0x0 in section `.ctors'
collect2.exe: error: ld returned 1 exit status
makefile:24: recipe for target 'faith.exe' failed
make: *** [faith.exe] Error 1

如果我已经在头文件中指定了实现函数,我不知道为什么会发生这种情况,我与析构函数有什么关系?

【问题讨论】:

  • 你在哪里实现~Queue()
  • ~Queue() 似乎没有定义。你定义了吗?
  • 那是错误,我做了 ~Queue(){};但因为我没有在 main 中做任何更改,它仍然给我同样的错误。

标签: c++ templates


【解决方案1】:
~Queue();

不一样

~Queue() {};

第二个实现~Queue,第一个只是声明它。

您声明了一个~Queue,但没有在任何地方定义它。您的 main 销毁了 Queue,它隐式调用了 ~Queue。链接器试图找到它,但找不到它,然后给你一个错误。

【讨论】:

  • 就是这样,我什至这样做了,但是因为我没有对 main 进行任何更改,所以它正在编译与以前相同的代码。
【解决方案2】:

在 C++ 中,声明和定义之间有明显的区别。在您的头文件中,声明了析构函数 ~Queue()。但是析构函数~Queue的定义却无处可寻。编译实际上是成功的,但如果在这种情况下找不到您的析构函数的实现,链接器会抱怨。

【讨论】:

    猜你喜欢
    • 2012-02-03
    • 2014-04-30
    • 2012-05-24
    • 2012-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多