C++将数组直接传递到函数中,而不首先初始化它
C++ Passing an array directly into a function without initializing it first
假设您已经创建了这个函数:
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});
相关文章:
- 正在初始化函数指针的constexpr数组
- 我应该在C++中使用构造函数还是初始化函数
- 使用 extern const 初始化函数
- 初始化函数中的静态变量,而不是在文件开始时
- 如何初始化函数中指针数组的大小
- 正在初始化初始化函数中的静态类成员
- call_once初始化函数
- SWIG + CMAKE:缺少初始化函数
- 如何创建在 c++ 中只读取一次的初始化函数
- 类内的强制初始化函数
- 使用元编程在编译时初始化函数数组
- 数组初始化函数:将数组作为指针传递:C++
- 从nodejs模块初始化函数报告失败
- 导入错误:动态模块未定义初始化函数
- 大括号初始化函数指针数组:从 'void (*(*)())()' 到 'void (*)()' 的转换无效
- 奇怪的行为,用 int 初始化函数指针
- 使用 init_seg 调用初始化函数
- 正在初始化函数内部的std::数组
- 初始化函数内部的指针.它是如何工作的
- JNI初始化函数以及缓存类和字段