C++将数组直接传递到函数中,而不首先初始化它

C++ Passing an array directly into a function without initializing it first

本文关键字:初始化 函数 数组 C++      更新时间:2023-10-16

假设您已经创建了这个函数:

void function(int array1[2], int array2[2])
{
    // Do Something
}

有可能在C++中做这样的事情吗

function([1,2],[3,4]);

或者这可以更好地描述为

function({1,2},{3,4});

我所知道的实现这一目标的唯一方法是:

int a[2] = {1,2};
int b[2] = {3,4};
function(a,b);

在c++11中,您可以这样做:

void function(std::array<int, 2> param1, std::array<int, 2> param2)
{
}

称之为

function({1,2}, {3,4});

如果出于某种原因不想使用std::array,在C++11中,您可以通过常量引用传递数组:

// You can do this in C++98 as well
void function(const int (&array1)[2], const int (&array2)[2]) {
}
int main() {
    // but not this
    function({1, 2}, {3, 4});
}

为了可读性,function可以重写为:

typedef int IntArray[2];
// or using IntArray = int[2];
void function(const IntArray& array1, const IntArray& array2) {
}

我认为你给出的例子也不适用于Moustach的答案。

c++中的function只接受你赋予它的类型

void function(int array1[2], int array2[2])
{
    // Do Something
}

您指定参数必须是int的指针。当您像[2,3]{2,3}那样编写时,它们实际上不是任何类型。我们之所以可以像int a[2] = {2,3}一样编写,是因为在c++中,每种类型的=操作都有构造函数。此构造函数以{2,3}为参数来构造数组,并将其赋给=操作数之前的变量。

所以这里的问题是=操作不返回任何内容,所以如果给它一个参数,它是不可接受的:int a = 0,这不会向函数返回a

但这里还有一些其他有趣的函数,它确实返回了一些东西,所以它们可以用作参数。

void somefunction(int a) {
    printf("This is the argument: %d!n" a);
}
int main() {
    somefunction(printf("Guess if I could compile and run!n"));
    return 0
}

这是一个非常简单的例子。你可以试着自己运行这个,如果我键入正确(我没有用这个代码在编译器中编译,但有类似的代码),这应该会打印出两行:

Guess if I could compile and run!
This is the argument: (somenumber)!

这是因为函数printf总是返回它打印的字符数,尽管在大多数情况下我们并不关心它。因此,在这里,只要thing(可以是任何东西,函数或变量)给函数提供相同类型的参数,函数就会接受它,否则,它就不会让你通过编译。

希望这能有所帮助。

我已经有一段时间没有做C++了,但如果我没记错的话,如果没有传递到函数中,你可以为参数指定默认值。我想你可以对数组值而不是int做同样的事情。参见下面的例子。

function(int a = 1, int b = 2);
function(int a [5] = { 16, 2, 77, 40, 12071}, int b[1] = {2});