繁体   English   中英

如何调用 C++ function?

[英]How to invoke C++ function?

我有一个原型为 function

void test( int array [] , int b); 

我知道我们可以将原型替换为: void test(int*, int);

main()中,我们声明了以下 arrays:

int array1[10], array2[10];

要将 function 的主体设置为 0,

test ( array1 , b)
{
for ( int i = 0 ; i < b ; i++)
  array1[i] = 0;

}

我可以这样做吗?为什么?

int main()
{// assuming b is the size of the array
test(array1 , b);
test(array2 , b) ;
return 0;
}

我知道 c++ 的基本知识,我正在尝试编写自己的包含文件。 我只是想知道这是否可能,这是一个不错的选择吗?

不是对您的问题的直接回答,但是您谈论 C++ 却使用普通的旧 C arrays 的事实引起了我的注意:

首先考虑不使用 C arrays。 相反,使用std::vector<int> 这可能避免了首先提出这个问题的需要(并且它避免了很多其他问题)。 您无需担心正确的尺寸类型( intsize_t ?其他?),因为std::vector已经为您提供了正确的类型: std::vector<int>::size_type

您的 function 签名将是

void test( std::vector<int> &a );

用零填充向量的实现将是:

void test( std::vector<int> &a )
{
  std::fill( a.begin(), a.end(), 0 );
}

是的,这是可能的; 但 function 正文中的声明应与您声明为原型的内容相同:

void test (int array1[], int b) // <---- see here (prefer `unsigned int` for size)
{
  for ( int i = 0 ; i < b ; i++)
    array1[i] = 0;
}

如果要将某些内容设置为0 ,最好使用库 function memset()

(作为建议,您可以在已经存在的基础上构建一个库。否则就像重新发明轮子一样。)

您可能会问形式参数和实际参数之间的区别。

在您的原型中

void test(int *array, size_t size);

名称“array”和“size”是形式参数。 您在 function 的正文中使用这些名称。

在调用function的代码中,可以使用不同的名称,即实际参数。

所以

int main()
{
   const size_t b = 10;
   int array1[10], array2[10];
   test(array1 , b);
   test(array2 , b) ;
   return 0;
}

这里array1b是第一次调用的实际参数, array2b是第二次调用的实际参数。

所以是的,您可以使用任何您喜欢的名称作为实际参数,只要变量的类型与您的原型匹配。

看起来您正在从 C 迁移。 是的,这是可能的,但您需要正确声明,否则编译器会抛出错误。

首选的 C++ 原型是

void test(int *array, size_t size);

在 C++ 中,您必须声明返回类型,以及原型和实现中每个参数的类型。

注意:您不需要使用size_t ,但它是首选(即使在 C 上)。 size_t包含在stddef.h中(扩展名为cstddef ,这是首选的 C++ 包含)。 它依赖于体系结构,通常在 32 位系统中为 unsigned int,在 64 位系统中为 unsigned long long

暂无
暂无

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

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