我正在尝试用 C++ 编写二叉树实现,并且正在使用 Google Test 对其进行测试。为了测试有序遍历,我对类进行了子BTree
类化,以便我可以覆盖该visit()
方法,以便我可以输出到字符串而不是控制台。问题是我想使用现有逻辑向树中插入新节点,并且它插入的是基类而不是派生类,即使我将指向派生对象的指针传递给该insert()
方法。有没有办法让它为所有节点插入派生类?
这是测试用例:
TEST_F(BTreeTestSuite, inOrder)
{
class InOrderTest : public BTree
{
public:
InOrderTest(int data) throw(int) : BTree(data), itsVisitString() {};
virtual ~InOrderTest() {};
std::string visitString(void) const { return itsVisitString; }
virtual void visit()
{
std::ostringstream oss;
oss << itsData;
itsVisitString += oss.str();
std::cerr << "vs1: " << itsVisitString << '|' << std::endl;
itsVisitString += " ";
std::cerr << "vs2: " << itsVisitString << '|' << std::endl;
}
private:
std::string itsVisitString;
};
InOrderTest iot(20);
iot.insert(new InOrderTest(30));
iot.insert(new InOrderTest(15));
iot.insert(new InOrderTest(10));
iot.inOrder();
EXPECT_STREQ("10 15 20 30 ", iot.visitString().c_str());
}
这是基类的相关部分:
class BTree
{
public:
BTree(int data) throw(); // constructor(s)
~BTree() throw(); // destructor
virtual void insert(BTree *node);
unsigned count() const;
void inOrder();
virtual void visit();
int data() const throw() { return itsData; };
BTree *left() const throw() { return itsLeft; };
BTree *right() const throw() { return itsRight; };
protected:
int itsData;
private:
// Don't allow creation of BTree without data
BTree() throw(); // constructor(s)
BTree *itsLeft;
BTree *itsRight;
};
...
BTree::BTree(int data) throw() : itsData(data)
{
itsLeft = itsRight = 0;
}
void BTree::insert(BTree *node)
{
if (node->itsData < itsData)
{
std::cerr << "Inserting data on the left\n";
if (itsLeft)
{
itsLeft->insert(node);
}
else
{
itsLeft = new BTree(node->itsData);
}
}
if (node->itsData > itsData)
{
std::cerr << "Inserting data on the right\n";
if (itsRight)
{
itsRight->insert(node);
}
else
{
itsRight = new BTree(node->itsData);
}
}
/* Drop value if it already exists in tree. */
}
void BTree::inOrder()
{
if (itsLeft) itsLeft->inOrder();
visit();
if (itsRight) itsRight->inOrder();
}
void BTree::visit()
{
cout << "base-visit: " << itsData << endl;
}