C ++如何访问从函数返回的对象的数据成员?
C++ How to access data member of an object returned from a function?
我有以下代码,如果 word/key 已经存在,它会简单地检查 AVL 树。如果它这样做 returns 指向该节点的指针,否则它 returns null:
void fileInput::testFunction() {
node newWord;
newWord.key = "test";
newWord.wordCount = 1;
tree.AVL_Insert(newWord);
if ((verifyWord("test").wordCount) != NULL) {
//insert increment wordCount code here;
}
}
这是节点结构:
struct node {
string key;
int wordCount;
};
这是 verifyWord 函数
node fileInput::verifyWord(string a) {
node b;
tree.AVL_Retrieve(a, b);
return b;
}
这是 AVL_Retreive 函数:
template <class TYPE, class KTYPE>
bool AvlTree<TYPE, KTYPE>
:: AVL_Retrieve (KTYPE key, TYPE& dataOut)
{
NODE<TYPE> *node;
if (!tree)
return false;
node = _retrieve (key, tree);
if (node)
{
dataOut = node->data;
return true;
} // if found
else
return false;
} // AVL_Retrieve
我的问题是如何在 testFunction()
的 if 语句中增加返回对象的 wordCount
您需要更改每个函数中的代码,以便 AVL_Retrieve()
return 如果找到该节点,则为指向该节点的指针,如果未找到,则为 NULL。然后 verifyWord()
将 return 完全相同的指针。然后您可以使用该指针修改节点。像这样:
if (node* nn = verifyWord("test")) {
nn->wordCount++;
}
node* fileInput::verifyWord(string a) {
return tree.AVL_Retrieve(a);
}
template <class TYPE, class KTYPE>
TYPE* AvlTree<TYPE, KTYPE>
:: AVL_Retrieve (KTYPE key)
{
if (!tree)
return NULL;
if (NODE<TYPE> *node = _retrieve (key, tree))
return node->data;
else
return NULL;
}
我有以下代码,如果 word/key 已经存在,它会简单地检查 AVL 树。如果它这样做 returns 指向该节点的指针,否则它 returns null:
void fileInput::testFunction() {
node newWord;
newWord.key = "test";
newWord.wordCount = 1;
tree.AVL_Insert(newWord);
if ((verifyWord("test").wordCount) != NULL) {
//insert increment wordCount code here;
}
}
这是节点结构:
struct node {
string key;
int wordCount;
};
这是 verifyWord 函数
node fileInput::verifyWord(string a) {
node b;
tree.AVL_Retrieve(a, b);
return b;
}
这是 AVL_Retreive 函数:
template <class TYPE, class KTYPE>
bool AvlTree<TYPE, KTYPE>
:: AVL_Retrieve (KTYPE key, TYPE& dataOut)
{
NODE<TYPE> *node;
if (!tree)
return false;
node = _retrieve (key, tree);
if (node)
{
dataOut = node->data;
return true;
} // if found
else
return false;
} // AVL_Retrieve
我的问题是如何在 testFunction()
的 if 语句中增加返回对象的 wordCount您需要更改每个函数中的代码,以便 AVL_Retrieve()
return 如果找到该节点,则为指向该节点的指针,如果未找到,则为 NULL。然后 verifyWord()
将 return 完全相同的指针。然后您可以使用该指针修改节点。像这样:
if (node* nn = verifyWord("test")) {
nn->wordCount++;
}
node* fileInput::verifyWord(string a) {
return tree.AVL_Retrieve(a);
}
template <class TYPE, class KTYPE>
TYPE* AvlTree<TYPE, KTYPE>
:: AVL_Retrieve (KTYPE key)
{
if (!tree)
return NULL;
if (NODE<TYPE> *node = _retrieve (key, tree))
return node->data;
else
return NULL;
}