I'm trying to pass the second argument optional to my search function:

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

If I call with one parameter, I want it to set it to root. I tried defult parameter in declaration, default parameter in implementation, both(I know its not true), two declaration. Nothing worked. Any ideas? I don't want overloading method beacuse it is the only line that will change.

Thanks.

有帮助吗?

解决方案

Use:

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

and handle the case of NULL pointer in the body of the function:

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

Or it can be set in the implementation part too, but just with NULL.

其他提示

A non-static member variable can not be used as a default argument.

Below is the relevant section in 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 is a non-static member variable here -- hence you can not specify it as a default argument.

This is a classic example of where you actually would gain from using an overload:

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

and then

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

Hereby you explicitly state, that when no parameter is given, you should use root as the value for curr_node.

There is no need to make a runtime test, when the code can be decided at compile time, and you don't have to write NULL when you actually mean root.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top