C++ 使用模板返回节点指针
试图在树中搜索特定节点,我需要在找到该节点时返回指向该节点的指针。这些节点属于名为C++ 使用模板返回节点指针,c++,templates,C++,Templates,试图在树中搜索特定节点,我需要在找到该节点时返回指向该节点的指针。这些节点属于名为BudgetDevelope的派生类类型,我收到的错误为: 无法使用节点类型的左值初始化类型为BudgetDevelope的返回对象 模板 T*Tree::find(节点*ptr,T值){ 如果(ptr!=NULL){ 如果(ptr->value==值){ 返回ptr;值){ 返回查找(ptr->左,值); } 否则{ 返回查找(ptr->右,值); } } } 否则{ 返回NULL; } } 我的理解是,由于
BudgetDevelope
的派生类类型,我收到的错误为:
无法使用节点类型的左值初始化类型为BudgetDevelope
的返回对象
模板
T*Tree::find(节点*ptr,T值){
如果(ptr!=NULL){
如果(ptr->value==值){
返回ptr;值){
返回查找(ptr->左,值);
}
否则{
返回查找(ptr->右,值);
}
}
}
否则{
返回NULL;
}
}
我的理解是,由于节点的类型与我返回的指针的类型相同,所以它应该可以工作。我如何解决这个问题
编辑:更多信息。
当我将返回类型更改为节点*
时,我使用此方法的文件会给我另一个错误
void EnvelopeBox::deposit(int id, double amount){
BudgetEnvelope searchKey = *new BudgetEnvelope(id, "searchKey");
BudgetEnvelope* keyPtr = envelopes.find(searchKey); <----same error
keyPtr->deposit(amount);
}
作废信封盒::存款(整数id,双倍金额){
BudgetDevelope searchKey=*新BudgetDevelope(id,“searchKey”);
BudgetDevelope*keyPtr=信封。查找(搜索键);存款(金额);
}
deposit
方法是在BudgetDevelope
类中定义的,而不是节点
,因此如果我将keyPtr
更改为相同类型的节点*
,我将无法访问deposit
方法 我认为您希望返回Node*
而不是T*
,因为ptr
属于Node*
e、 g
到
您需要做的是访问节点内的数据。
或者,您可以从find
函数返回ptr->Value
。ptr
是指向类型节点的指针,该函数返回指向类型T
的指针。类型T
和Node
是不同的
如果要返回T*
则应返回节点
类中的任何方法,该方法返回指向该节点
中包含的值的指针。否则,我认为这就是您想要的,更改T*Tree::find(Node*ptr,T value)
的签名以返回Node*
,正如Justin建议的那样。是类树中定义的类节点
?(答案越快,您应该返回一个指向节点的指针,而不是指向T
)信封的类型是什么?信封是我正在搜索的树。我确实尝试过,但它在另一个文件中给了我一个错误。我将编辑我的帖子来展示接下来会发生什么。我已经根据你的新信息更新了我的答案。
void EnvelopeBox::deposit(int id, double amount){
BudgetEnvelope searchKey = *new BudgetEnvelope(id, "searchKey");
BudgetEnvelope* keyPtr = envelopes.find(searchKey); <----same error
keyPtr->deposit(amount);
}
Node<T>* Tree<T>::find( Node<T> * ptr, T value)
BudgetEnvelope* keyPtr = envelopes.find(searchKey);
Node<BudgetEnvelope>* keyPtr = envelopes.find(searchKey);
BudgetEnvelope myValue = keyPtr->Value;
myValue.deposit(amount)