Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

assignment operator within function parameter C++

I'm studying data structures (List, Stack, Queue), and this part of code is confusing me.

ListNode( const Object& theElement = Object(), ListNode * node = NULL);


template<class Object>
ListNode<Object>::ListNode( const Object& theElement, ListNode<Object> * node) {
    element = theElement;
    next = node;
}
  1. Why there are assignment operators within function parameters?
  2. What does Object() call do?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Those are not assignment operators. Those are default arguments for the function.

A function can have one or more default arguments, meaning that if, at the calling point, no argument is provided, the default is used.

void foo(int x = 10) { std::cout << x << std::endl; }

int main()
{
  foo(5); // will print 5
  foo(); // will print 10, because no argument was provided
}

In the example code you posted, the ListNode constructor has two parameters with default arguments. The first default argument is Object(), which simply calls the default constructor for Object. This means that if no Object instance is passed to the ListNode constructor, a default of Object() will be used, which just means a default-constructed Object.

See also:
Advantage of using default function parameter
Default value of function parameter


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...