Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有一个基类,其中有两个继承自此的类,还有两个继承自这些的类。我需要使用二叉树来存储数据,但是我不太明白如何将数据存储在树中。在我看到的示例中,数据只是一个,int data但我的数据最多可以是四种不同的类型。
int data
如果您想要存储在树中的所有类型都派生自同一个基类,那么您的数据成员可以是指向该基类的指针。这样,指针可以指向基类的对象或任何派生类型。
例如:
class Node { ... private: Vehicle* mData; };
然后您可以执行以下操作:
node->SetData(new Car); otherNode->SetData(new Moped);
或您拥有的任何接口,将 mData 指针设置为指向从 Vehicle 派生的类树中某种类型的对象。