繁体   English   中英

使数组成为 C++ 函数的可选参数

[英]Make an array an optional parameter for a c++ function

在 C++ 中,您可以将参数设为可选,如下所示:

void myFunction(int myVar = 0);

你如何用数组做到这一点?

void myFunction(int myArray[] = /*What do I put here?*/);

您可以使用nullptr或指向全局常量数组的指针来表示默认值:

void myFunction(int myArray[] = nullptr ) {
                             // ^^^^^^^
}

这是因为int myArray[]在用作函数参数时被类型调整为int*指针。

默认参数必须具有静态链接(例如是一个全局链接)。 下面是一个例子:

#include <iostream>

int array[] = {100, 1, 2, 3};

void myFunction(int myArray[] = array)
{
    std::cout << "First value of array is: " << myArray[0] << std::endl;
    // Note that you cannot determine the length of myArray!
}

int main()
{
    myFunction();
    return 0;
}

如果默认数组足够小(注意:它可以小于实际数组类型的大小),因此复制它不是问题,那么(C++11 起) std::array可能是最具表现力的, “C++-ish”风格(正如 Ed Heal 在评论中暗示的那样)。 除了每个无参数f()调用的 copy-init 负担外,使用默认值,数组本身具有与内置的类 C 数组相同的性能属性,但它不需要笨拙的、单独定义的默认值变量:

#include <array>

// Just for convenience:
typedef std::array<int, 3> my_array;

void f(const my_array& a = {1, 2, 3});

(注意:通过 const ref. 至少在那些你明确传递参数的情况下避免了复制。)

好吧,在现代 C++ 17 中,您可以使用std::optional

std::optional<std::array<int,4>> oa;

// ...

if ( oa )
{
    // there is content in oa
    *oa // get the content
}
else
{
    // there is no content inside oa
}

我使用std::array作为std::array表示,但您也可以使用原始数组、向量等。

暂无
暂无

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

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