C++如何将一个函数用于另一个变量?
如何在不创建新函数的情况下将函数 output_integer 用于数组 v?我需要打印 v 中最终的值,但我想使用与 m 相同的函数:
#include <iostream>
#include <cmath>
using namespace std;
int m[10];
int v[10];
void input_integer()
{
for (int i=0; i<10; i++)
{
cout<<"Element "<<i+1<<"=";
cin>>m[i];
}
}
void output_integer()
{
cout<<"The values of the array are:\n";
for (int i=0; i<10; i++)
{
cout<<"Element "<<i+1<<" = "<<m[i]<<"\n";
}
}
void copy_div3()
{
int k=0;
for (int i=0; i<10; i++)
{
if (m[i]%3==0)
{
v[k]=m[i];
k++;
}
}
}
int main()
{
//input_integer();
output_integer();
copy_div3();
return 0;
}
How can I use my function output_integer for the array v, without making a new function? I need to print the values that end up in v, but i want to use the same function as i do for m:
#include <iostream>
#include <cmath>
using namespace std;
int m[10];
int v[10];
void input_integer()
{
for (int i=0; i<10; i++)
{
cout<<"Element "<<i+1<<"=";
cin>>m[i];
}
}
void output_integer()
{
cout<<"The values of the array are:\n";
for (int i=0; i<10; i++)
{
cout<<"Element "<<i+1<<" = "<<m[i]<<"\n";
}
}
void copy_div3()
{
int k=0;
for (int i=0; i<10; i++)
{
if (m[i]%3==0)
{
v[k]=m[i];
k++;
}
}
}
int main()
{
//input_integer();
output_integer();
copy_div3();
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使
output_integer
将数组作为参数,以便您可以向其传递任何数组Make the
output_integer
to take the array as parameter, so that you can pass it any array您可以更改函数签名以获取数组参数并打印它,而不是依赖变量的全局性。
为了使其更通用,您甚至可以考虑将其设为
模板
:You can change the function signature to take the array argument and print it, instead of relying on the global-ness of the variable.
To make it more generic, you can even think of making it a
template
:只需提供指向该数组及其大小的指针:
用法:
Just provide a pointer to that array and its size:
usage:
您可以将参数传递给函数。
像这样定义 `output_integer:
然后像这样调用它:
实际上,将
m
和v
数组完全移出全局范围可能是一个很好的练习。仅在main
函数内定义它们,以便将它们作为参数传递给需要访问它们的任何函数。You can pass arguments to functions.
Define `output_integer like this:
And then call it like this:
Actually, it would probably be a good exercise to move the
m
andv
arrays away from the global scope entirely. Define them only inside themain
function so that they have to be passed as parameters to any function that needs to access them.您需要了解函数的基本概念:所有逻辑都应依赖于传递给函数的参数(如果是非成员)。你有一个自由函数(不是类的一部分),所以如果你需要打印一个数组,你应该将该数组作为参数传递:
由于你使用c++,我还建议使用
std::vector
而不是数组:完成更改后,用 google 搜索“神奇参数”。
You need to understand the basic concept of functions: all logic should depend on parameters passed to the functions (if non-member). You have a free function (not part of the class), so if you need to print an array, you should pass that array as a parameter:
Since you use c++, I also suggest using
std::vector
instead of arrays:When you're done with the changes, google for "magic parameters".