感谢您的关注!我是C ++的新手,这让我很疯狂。 这是编译结果:
$ g++ -std=c++11 main.cpp Node.cpp
C:\Users\Sen\AppData\Local\Temp\ccsNgEyE.o:main.cpp:(.text+0x29): undefined reference to `Node<int>::Node()'
C:\Users\Sen\AppData\Local\Temp\ccsNgEyE.o:main.cpp:(.text+0x43): undefined reference to `Node<int>::setItem(int const&)'
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe:
C:\Users\Sen\AppData\Local\Temp\ccsNgEyE.o: bad reloc address 0x0 in section `.ctors'
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: final link failed: Invalid operation
collect2.exe: error: ld returned 1 exit status
以下是我的文件: Node.h :
#ifndef NODE_H
#define NODE_H
template <class ItemType>
class Node{
private:
ItemType item;
Node<ItemType>* next;
public:
Node();
Node(const ItemType& anItem);
Node(const ItemType& anItem, Node<ItemType>* nextNodePtr);
void setItem(const ItemType& anItem);
void setNext(const Node<ItemType>* nextNodePtr);
ItemType getItem() const;
Node<ItemType>* getNext() const;
};
#endif
Node.cpp :
#include "Node.h"
using namespace std;
template <class ItemType>
Node<ItemType>::Node(){
next = nullptr;
}
template <class ItemType>
Node<ItemType>::Node(const ItemType& anItem){
item = anItem;
next = nullptr;
}
template <class ItemType>
Node<ItemType>::Node(const ItemType& anItem, Node<ItemType>* nextNodePtr){
item = anItem;
next = nextNodePtr;
}
template <class ItemType>
void Node<ItemType>::setItem(const ItemType& anItem){
item = anItem;
}
template <class ItemType>
void Node<ItemType>::setNext(const Node<ItemType>* nextNodePtr){
next = nextNodePtr;
}
template <class ItemType>
ItemType Node<ItemType>::getItem() const{
return item;
}
template <class ItemType>
Node<ItemType>* Node<ItemType>::getNext() const{
return next;
}
我的 main.cpp 文件:
#include <iostream>
#include <vector>
#include "Node.h"
int main(){
Node<int>* node1 = new Node<int>();
node1->setItem(1);
}
我根本不知道为什么......在我在Node.cpp和Node.cpp中添加的g ++命令中,显然有构造函数和方法的实现。 谢谢你的关注!