繁体   English   中英

为什么我不能在C ++中的函数中使用outf

[英]Why can't I use outf in a function in C++

我想在函数中使用outf ,但是当我尝试使用它时却显示“未定义”错误。

我使用Visual Studio 2013,这是我的代码

int main(){

int costumer;
int d;
cout <<"Enter Number : ";
cin >> costumer;
d = costumer; 
int *Erand = new int[d]; //Random Number 1
int *Srand = new int[d]; //Random Number 2
int *SumArrays = new int[d]; // sum Array 
ofstream outf("Sample.dat");

//------------------------- Make Random Numbers

srand(time(0));
for (int  i = 0; i< d; i++)
{
    Erand[i] = 1 + rand() % 99;
}
for (int i = 0; i< d; i++)
{
    Srand[i] = 1 + rand() % 999;
}
//---------------------------- Out Put 
outf << "Random Number 1 " << endl;
for (int i = 0; i < d; i++) // i want it in a function
{
    outf << Erand[i];
    outf << ",";
}
outf << endl;

outf << "Random Number 2 " << endl;
for (int i = 0; i < d; i++)// i want it in a function
{
    outf << Srand[i];
    outf << ",";
}
outf << endl;
//--------------------------------calculator -------------------------
for (int  i = 0; i < d; i++)
{
    SumArrays[i] = Erand[i] + Srand[i];
}
outf << "Sum Of Array is : ";
outf << endl;
for (int  i = 0; i < d; i++)
{
    outf << SumArrays[i];
    outf << ",";
}
outf << endl;
delete[] Erand;
delete[] Srand;
delete[] SumArrays;}

例如我想在函数中使用随机数1:

void Eradom(){
for (int i = 0; i < d; i++)
{
    outf << Erand[i];
    outf << ",";
}

但我在第4行出现错误。

outfmain函数中的局部变量。 为了使其可以被其他函数访问,您可以将其定义为全局变量(通常不建议使用),也可以将其显式传递给Erandom函数。

您可以在main()定义outf ,但是尝试在函数Erandom()访问它。 这是导致此错误的原因。 您必须将其作为参数传递给函数Erandom()

您的outf变量是main的局部变量,因此在Erandom函数中不可见。 要将变量传递到函数中,请按如下方式定义

void Eradom(std::ostream &outf) {
  for (int i = 0; i < d; i++) {
    outf << Erand[i];
    outf << ",";
  }
}

并从主叫它

Eradom(outf);

暂无
暂无

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

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