[英]Using recursion in C++ class - Passing its own data member
I am writing a pre-order traversal for Tree class:我正在为Tree类编写一个预序遍历:
class Tree {
public:
...
void preOrder(TreeNode* root)
{
if (root != nullptr)
{
cout << root->key << " ";
preOrder(root->left);
preOrder(root->right);
}
}
private:
TreeNode* root = nullptr;
}
I want to pass Tree 's root data member to preOrder so that in main.cpp , I call the function like this:我想将Tree的根数据成员传递给preOrder以便在main.cpp 中,我像这样调用函数:
Tree.preOrder();
So I code like this所以我这样编码
void preOrder(TreeNode* root = this->root)
but compiler generate error但编译器产生错误
'this' may only be used inside a nonstatic member function
'this' 只能在非静态成员函数中使用
Is there anyway to fix this?有没有什么办法解决这一问题? Or I am going to use iterative instead of recursive traversal.
或者我将使用迭代而不是递归遍历。
Like the error message says, you can't use this
in a method parameter.就像错误消息所说的那样,您不能在方法参数中使用
this
。 Just define a 0-parameter overload of preOrder()
that calls the 1-parameter version.只需定义调用 1 参数版本的
preOrder()
的 0 参数重载。
class Tree {
public:
...
void preOrder()
{
preOrder(root);
}
void preOrder(TreeNode* aRoot)
{
if (aRoot)
{
cout << aRoot->key << " ";
preOrder(aRoot->left);
preOrder(aRoot->right);
}
}
private:
TreeNode* root = nullptr;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.