函数参数C ++中的赋值运算符 [英] assignment operator within function parameter C++

查看:203
本文介绍了函数参数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. 为什么函数参数中包含赋值运算符?
  2. Object()调用做什么?
  1. Why there are assignment operators within function parameters?
  2. What does Object() call do?

推荐答案

这些不是赋值运算符.这些是 默认参数 的功能.

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
}

在您发布的示例代码中,ListNode构造函数有两个带有默认参数的参数.第一个默认参数是Object(),它仅调用 Object的> 默认构造函数 .这意味着如果没有Object实例传递给ListNode构造函数,则将使用默认值Object(),这仅表示默认构造的Object.

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

这篇关于函数参数C ++中的赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆