为什么使用this指针作为默认参数不允许使用?

Ksh*_*jee 2 c++ default-value

我只是在我的Binary树上写了一个inorder函数,我遇到了这个难题.

class BinaryTree
{
private:
     struct Node* o_root;
public:
BinaryTree()
    {
              o_root = new Node();    
        o_root->data = 0;
        o_root->left = NULL;
        o_root->right = NULL;

    }
    void inorder(Node*root = o_root);//Invalid

};


void BinaryTree::inorder(Node* root = o_root)//Invalid
    {
         if(root==NULL)
         {
             return;
         }
         inorder(root->left);

         cout<< root -> data;

         inorder(root->right);

    }
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:非静态成员引用必须与特定对象相关

如果我将根节点静态这是有效的.

为什么会这样?如果我有两个二叉树,我会想要对象的特定根,而不是静态成员.我尝试使用这个运算符,但这给了我另一个错误,基本上说在默认参数中不允许使用此运算符.

任何人都可以解释为什么这不起作用以及为什么C++拒绝使用此运算符作为默认参数?

Mar*_*rio 5

这是因为this当实际调用该方法时,未定义也不存在(想象生成的代码).对于实际的成员变量也是如此(没有指向数据的指针,也无法访问数据).

为了详细说明这一点,它还会导致奇怪的结构没有真正定义,如下所示(记住它o_root甚至是私有的!):

sometree->inorder();
// ...would essentially be the same as...
sometree->inorder(sometree->o_root);
Run Code Online (Sandbox Code Playgroud)

如何重载inorder(),删除默认参数?

基本上使用以下内容:

void BinaryTree::inorder(void)
{
    inorder(o_root);
}

void BinaryTree::inorder(Node* root)
{
    // your code as-is
}
Run Code Online (Sandbox Code Playgroud)

  • 或者在编写时,你可以使`inorder`成为`Node`的函数来完成实际的工作,然后`void BinaryTree :: inorder(void){o_root-> inorder());`.用户可以调用`some_root-> inorder();而不是调用`mytree.inorder(some_root);`. (2认同)