刚刚完成创建我的二叉树类仅意识到我应该将其作为模板。我花了几个小时试图将其转换为模板,但是我一直在收到大量的错误,从“模板名的无效使用”到“成员的额外限定”。我对模板的概念很陌生,但我对我想要达到的目标有一个概念。将C++类转换为模板类
BTree.cpp
#include <iostream>
#include <string>
#include "BTree.h"
using namespace std;
BTree::BTree(board startboard, string startplayer)
{
treeboard = startboard;
player = startplayer;
root = new BTNode(treeboard, player,-1,-1);
}
BTree::~BTree()
{
delete root;
}
int BTree::sumtree()
{
if (root->getvalue(-1) > root->getvalue(1))
return root->getchildposition(-1);
else
return root->getchildposition(1);
}
BTree.h
#include <string>
#include "BTNode.h"
#include "board.h"
using namespace std;
class BTree
{
public:
BTree(board startboard, string startplayer);
~BTree();
int sumtree();
private:
string player;
board treeboard;
BTNode *root;
};
'startplayer' 是目前一个字符串,我想这是通用模板类型。
将我的过程转换为单个模板文件应该如何?
首先实现这个非模板并不难过。这叫做'提升'。创建一个仅仅处理'int'或'string'并使其正常工作的类通常更容易,然后提出一般形式。 http://www.generic-programming.org/about/intro/lifting.php – Steve 2014-11-02 04:09:14
为什么在构造函数中复制两次startboard和startplayer? – 2014-11-02 05:29:37
@NeilKirk从我大幅改变班级时的剩余代码,没有意识到那些行现在是多余的;感谢您的支持 – Matt 2014-11-02 05:43:26