gpt4 book ai didi

C++ 链接错误 : Undefined symbols using a templated class

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:06:56 25 4
gpt4 key购买 nike

我在编写的类中遇到了一些非常奇怪的链接错误。我完全找不到任何可以描述正在发生的事情的东西。

Visual Studio (Windows XP)

players.obj : error LNK2019: unresolved external symbol "public: __thiscall TreeNode::TreeNode(void)" (??0?$TreeNode@VPlayer@@@@QAE@XZ) referenced in function "public: __thiscall PlayerList::PlayerList(void)" (??0PlayerList@@QAE@XZ)

Xcode (OSX 10.5)

Undefined symbols: "TreeNode::~TreeNode()", referenced from: PlayerList::~PlayerList()in players.o

头文件:generics.h

class TreeNode : public BaseNode{
public:
const static int MAX_SIZE = -1; //-1 means any size allowed.
const static int MIN_SIZE = 0;
//getters
int size() const;
vector<C*> getChildren() const;
//setters
void setChildren(vector<C*> &list);
//Serialization
virtual void display(ostream &out) const;
virtual void read(istream &in);
virtual void write(ostream &out) const;
//Overrides so SC acts like an array of sorts.
virtual C* get(int id) const;
virtual int get(C *child) const;
virtual bool has(C *child) const;
virtual C* pop(int id);
virtual void push(C *child);
virtual TreeNode& operator<< (C *child); //append
virtual void remove(int id); //Clears memory
virtual void remove(C *child); //Clears memory
//Initalizers
TreeNode();
TreeNode(istream &in);
TreeNode(long id, istream &in);
TreeNode(BaseNode* parent, istream &in);
TreeNode(long id, BaseNode* parent);
TreeNode(long id, BaseNode* parent, istream &in);
~TreeNode();
string __name__() const{ return "TreeNode"; }
protected:
void clearChildren();
void initalizeChildren();
vector<C*> _children;
};

TreeNode 子类的代码

PlayerList::PlayerList() : TreeNode<Player>(){}
PlayerList::PlayerList(istream &in) : TreeNode<Player>(in){}
PlayerList::~PlayerList(){}

最佳答案

当你在 .cpp 文件中定义你的模板时,你必须使用已知模板将被使用的所有类型/模板参数显式实例化它,就像这样(将它放在 .cpp 文件中):

template class TreeNode<Player>;

如果您不知道模板将与哪些模板参数一起使用,则必须将所有定义放入标题中。喜欢

template<typename T>
class TreeNode {
public:
TreeNode() /* now, also put the code into here: */ { doSomething(); }
};

原因是当您要从某个地方使用模板时,编译器必须能够为模板的特定实例生成代码。但是,如果将代码放入 .cpp 文件并编译它,编译器就无法获取代码来生成实例化(除非使用臭名昭著的 export 关键字,它只有极少数编译器支持)。

这也是我的 C++ 陷阱答案中的一个条目:What C++ pitfalls should I avoid?

关于C++ 链接错误 : Undefined symbols using a templated class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/312115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com