在c ++中,你可以创建一个像这样的参数:
void myFunction(int myVar = 0);
你如何用数组做到这一点?
void myFunction(int myArray[] = /*What do I put here?*/);
答案 0 :(得分:11)
您可以使用nullptr
或指向全局const数组的指针来表示默认值:
void myFunction(int myArray[] = nullptr ) {
// ^^^^^^^
}
这是因为int myArray[]
在用作函数参数时被调整为int*
指针。
答案 1 :(得分:4)
默认参数必须具有静态链接(例如,是全局的)。 这是一个例子:
#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;
}
答案 2 :(得分:1)
如果 default 数组足够小(请注意:它可以小于实际数组类型的大小),那么复制它就不成问题了,(因为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。传递至少在那些确实显式传递参数的情况下避免了复制。)
答案 3 :(得分:0)
好吧,在现代 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
作为数组的表示,但您也可以使用原始数组、向量等。