c++ - 为什么不允许将 this 的指针用作函数的默认参数?

标签 c++ default-value

我刚刚为我的二叉树编写了一个有序函数,我遇到了这个困难。

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);

    }

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

如果我将根节点设为静态,这将起作用。

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

谁能解释为什么这不起作用以及为什么 C++ 拒绝将此运算符用作默认参数?

最佳答案

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

为了更详细地阐述这一点,它还会导致未真正定义的奇怪构造,如下所示(请记住 o_root 甚至是私有(private)的!):

sometree->inorder();
// ...would essentially be the same as...
sometree->inorder(sometree->o_root);

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

基本上使用以下内容:

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

void BinaryTree::inorder(Node* root)
{
    // your code as-is
}

关于c++ - 为什么不允许将 this 的指针用作函数的默认参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8851383/

相关文章:

c++ - 如果 lambda 使用 std::move() 捕获不可复制的对象,为什么它是不可 move 的?

c++ - std::align 和 std::aligned_storage 用于内存块的对齐分配

kotlin - 在 Kotlin 中访问函数的默认参数值

c++ - c++ 和其他语言有 fiddle 类型的东西吗?

c++ - float1 与 CUDA 中的 float

javascript - 当 GraphQL 值可能为空时将其与 React 一起使用

swift - 使用 UIViewController 作为可选参数的默认值,但出现 "X does not have a member named Y"错误

spring - 在 Spring 中将默认属性值指定为 NULL

VS2005 中的 C# : what do the following types default to in C#?

c++ - Perl 与 Ultraedit 脚本