【问题标题】:how to use default arguments in c++?如何在 C++ 中使用默认参数?
【发布时间】:2021-09-14 02:54:47
【问题描述】:

在python中我可以写:


def test(a, b=None):
    if b is None:
        return
    else:
        print(123)
    

在cpp中,最好避免使用指针,所以我改用引用,

那么如何做同样的事情呢?

#include "stdio.h"
void test(int a, const int &b) { 
// how to check ?? since b should not be nullptr
printf("123\n"); };
int main() { test(); }

【问题讨论】:

  • 引用永远不会为空。使用std::optional 表示可以为空的值。
  • 您从哪里得知最好避免使用指针?
  • 使用指针,而不是引用,仅此而已。

标签: python c++ default-arguments


【解决方案1】:

在cpp中,最好避免使用指针,所以我使用引用来代替

引用不能引用NULL,因此指针执行此操作的传统方式,例如void test(int a, const int *b=NULL)。鼓励在指针上引用的大部分原因是因为它使您无需处理NULL 参数;如果您需要 NULL 参数,引用并不能拯救您。

std::optional is sometimes used for similar scenarios,但它更新了很多(C++17),我认为它是否更可取并没有强烈的共识;也就是说,将其与 std::nullopt 一起使用作为默认值接近于您已经拥有的,并且是处理问题的合理方法。

替代方案(在上述链接问题的答案中提到)只是重载函数两次,一次有参数,一次没有;这可以与std::optional 方法结合使用,以允许只传递一个参数的用户更简单地调用(默认情况下,生成的代码内联在每个依赖它的调用站点创建默认参数),但仍实现该功能通过通用代码(单参数函数只是转身调用双参数函数)。

【讨论】:

    【解决方案2】:

    C++ 引用不能是NULL。它们始终指向有效对象,并在声明期间初始化。

    【讨论】:

      【解决方案3】:

      正如其他答案中提到的,C++ 中不允许使用 NULL 引用,因此您不能将 NULL 用作按引用参数的默认值,而 std::optional 将是一个不错的选择。

      您可以定义自己的哨兵对象,以执行与 NULL 相同的功能,而实际上不是 NULL 引用,如下所示:

      #include "stdio.h"
      
      const int & get_sentinel_ref()
      {
         static int sentinel = 0;  // must be declared static
         return sentinel;          // in order to have a fixed address
      }
      
      void test(int a, const int &b = get_sentinel_ref())
      {
         // Check if b is referring to our sentinel-value or not
         // Note that I'm comparing memory-addresses here, not values
         // otherwise the code would do the wrong thing if the user
         // passed in zero (or whatever dummy-value sentinel is set
         // to in the get_sentinel_ref() function above)
         if (&b == &get_sentinel_ref())
         {
            printf("a is %i, but you didn't supply a second argument!\n", a);
         }
         else
         {
            printf("a is %i, b is %i\n", a, b);
         }
      }
      
      int main(int, char **)
      {
         test(5);
         test(6,7);
         return 0;
      }
      

      ...运行时,上面的程序打印:

      a is 5, but you didn't supply a second argument!
      a is 6, b is 7
      

      【讨论】:

      • 它可以工作,但我认为它与 Python 代码相比太脏了。
      • 与 Python 代码相比,C++ 中的几乎所有内容都太脏了:)
      • 不,它不是更脏,它更明确;)
      猜你喜欢
      • 2010-11-15
      • 2011-02-19
      • 2012-11-20
      • 1970-01-01
      • 1970-01-01
      • 2012-08-01
      • 1970-01-01
      • 2013-02-20
      • 2011-07-04
      相关资源
      最近更新 更多