【问题标题】:Compiler error in default parameters in class类中默认参数中的编译器错误
【发布时间】:2013-11-06 11:36:37
【问题描述】:

我正在尝试将第二个可选参数传递给我的搜索功能:

class ExponentialTree
{
public:
node* Search(int num, node* curr_node=root);
void Insert(int num);

private:
node* root;
};

node* ExponentialTree::Search(int num, node* curr_node)
{

如果我使用一个参数调用,我希望它设置为 root。我在声明中尝试了默认参数,在实现中尝试了默认参数,两者(我知道它不是真的),两个声明。没有任何效果。有任何想法吗?我不想重载方法,因为它是唯一会改变的行。

谢谢。

【问题讨论】:

  • 从外部看不到根
  • AFAIK,在没有该参数的情况下使Search 重载的唯一选择。
  • 尝试将其设置为NULL,然后在第一次运行时将其设置为root
  • 谢谢。这就是解决它的原因。

标签: c++ class optional-parameters


【解决方案1】:

用途:

    node* Search(int num, node* curr_node=NULL);

并处理函数体中NULL指针的情况:

    node* Search(int num, node* curr_node)
    {
         if (curr_node == NULL){
               //...
         }
         //...
    }

或者它也可以在实现部分设置,但只是用NULL。

【讨论】:

  • 不错的一个!问题的根源是什么?编译器是否只识别常量或枚举值?
【解决方案2】:

非静态成员变量不能用作默认参数。

下面是C++ standard draft (N3225), section § 8.3.6, point 9:中的相关部分

.. a non-static 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). [ Example: the declaration of X::mem1() in the following
example is ill-formed because no object is supplied for the non-static member X::a used as an initializer.
int b;
class X {
int a;
int mem1(int i = a); // error: non-static member a
// used as default argument
int mem2(int i = b); // OK; use X::b
static int b;
};

root 在这里是一个非静态成员变量——因此您不能将其指定为默认参数。

【讨论】:

  • 感谢您提供令人难以置信的详细解释 :)
【解决方案3】:

这是一个典型的例子,说明您实际上会从使用重载中获得

node* Search(int num, node* curr_node) 
{
   // Your implementation
}

然后

inline node* Search(int num) { return Search(num, root); }

您在此明确声明,当没有给出参数时,您应该使用root 作为curr_node 的值。

没有必要进行运行时测试,代码可以在编译时确定,而实际上你的意思是root,你不必写NULL

【讨论】:

  • 我可以在类定义中写内联方法吗?
猜你喜欢
  • 2011-08-10
  • 2015-01-12
  • 2011-09-06
  • 2011-09-17
  • 2013-11-15
  • 2017-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多