简体   繁体   English

函数参数C ++中的赋值运算符

[英]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? Object()调用做什么?

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. 在您发布的示例代码中, ListNode构造函数有两个带有默认参数的参数。 The first default argument is Object() , which simply calls the default constructor for Object . 第一个默认参数是Object() ,它仅调用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 . 这意味着,如果没有将Object实例传递给ListNode构造函数,则将使用默认的Object() ,这仅意味着默认构造的Object

See also: 也可以看看:
Advantage of using default function parameter 使用默认功能参数的优势
Default value of function parameter 功能参数的默认值

The assignments in declarations provide default values for optional parameters . 声明中的分配为可选参数提供默认值。 Object() means a call to Object 's default constructor. Object()表示对Object的默认构造函数的调用。

The effect of the default parameters is as follows: you can invoke ListNode constructor with zero, one, or two parameters. 默认参数的效果如下:您可以使用零,一或两个参数来调用ListNode构造函数。 If you specify two parameter expressions, they are passed as usual. 如果指定两个参数表达式,则照常传递它们。 If you specify only one expression, its value is passed as the first parameter, and the second one is defaulted to NULL . 如果仅指定一个表达式,则将其值作为第一个参数传递,第二个参数默认为NULL If you pass no parameters, the first parameter is defaulted to an instance of Object created with its default constructor, and the second one is defaulted to NULL . 如果不传递任何参数,则第一个参数默认为使用其默认构造函数创建的Object的实例,第二个参数默认为NULL

请访问http://www.errorless-c.in/2013/10/operators-and-expressions.html ,以获取使用C编程语言编写的运算符和表达式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM