[英]Why using a pointer of this as default parameter to a function not allowed?
I was just writing an inorder function to my Binary tree and I have encountered this difficulty. 我只是在为二叉树编写一个有序函数,而我遇到了这个困难。
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);
}
I get an error : a nonstatic member reference must be relative to a specific object 我收到一个错误:非静态成员引用必须相对于特定对象
if I turn the root node static this works. 如果我将根节点设为静态,则可以正常工作。
Why should this be so ? 为什么会这样呢? If i have two binary trees I would want the specific root of the object, not a static member.
如果我有两个二叉树,我会想要对象的特定根,而不是静态成员。 I tried using a this operator but that gives me another error which basically says that use of this operator not allowed in default parameter.
我尝试使用this运算符,但这给了我另一个错误,该错误基本上表明默认参数中不允许使用此运算符。
Can anyone explain why this is not working and why has C++ denied use of this operator as default arguments? 谁能解释为什么这不起作用,为什么C ++拒绝使用此运算符作为默认参数?
That's because this
isn't defined nor does it exist, when the method is actually called (imagine the resulting code). 这是因为
this
是没有定义也不存在,当方法实际上是所谓的(想象得到的代码)。 Same is true for actual member variables (without the pointer to the data there's no way to access the data either). 实际的成员变量也是如此(没有指向数据的指针,也无法访问数据)。
To elaborate this a bit more, it would also result in weird constructs that aren't really defined, like the following (remember that o_root
is even private!): 为了更详细地说明这一点,还将导致未真正定义的怪异构造,例如以下内容(请记住,
o_root
甚至是私有的!):
sometree->inorder();
// ...would essentially be the same as...
sometree->inorder(sometree->o_root);
How about just overloading inorder()
, removing the default parameter? 仅重载
inorder()
删除默认参数如何?
Basically use the following: 基本上使用以下内容:
void BinaryTree::inorder(void)
{
inorder(o_root);
}
void BinaryTree::inorder(Node* root)
{
// your code as-is
}
You can actually narrow the problem down even further: 实际上,您可以进一步缩小问题的范围:
class A
{
int x;
void foo(int k = x);
};
This is because the standard says so. 这是因为该标准是这样说的。
You can overload the method, foo()
, and call foo(x)
inside. 您可以重载方法
foo()
,并在内部调用foo(x)
。
From 8.3.6/9 从8.3.6 / 9起
[...] A nonstatic member shall not be used in a default argument expression, even if it is not evaluated, unless it appears as the id-expression of a class member access expression (5.2.5) or unless it is used to form a pointer to member (5.3.1) [...]
[...]非静态成员不得在默认参数表达式中使用,即使未进行评估,除非它显示为类成员访问表达式(5.2.5)的id表达式,或者除非用于形成指向成员(5.3.1)的指针[...]
For insight, you can read the whole section 8.3.6 要了解情况,您可以阅读整个章节8.3.6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.