我有一个名为Random的类,其中包含以下变量
private:
int Numbers[10];
int NrHighest;
int NrLowest;
int Index;
int IndexH;
int IndexL;
和一个名为
friend void
insertNumbers(Random Random1)的 friend 函数`void insertNumbers(Random Random1)
{
string line;
int one,two,three;
int columOne[10];
int columTwo[10];
int columThree[10];
ifstream myfile("Numbers.dat");
if (myfile.is_open())
{
int i = 0;
while ( getline (myfile,line) )
{
sscanf(line.c_str(),"%i %i %i",&one,&two,&three);
columOne[i] = one;
columTwo[i] = two;
columThree[i] = three;
i++;
}
myfile.close();
}
else cout << "Unable to open file";
switch(run)
{
case 0 :
{
for(int i = 0;i < 10;i++)
{
Random1.Numbers[i] = columOne[i];
cout << Random1.Numbers[i] << endl;
};
break;
}
case 1 :
{
for(int i = 0;i < 10;i++)
{
Random1.Numbers[i] = columTwo[i];
cout << Random1.Numbers[i] << endl;
};
break;
}
case 2 :
{
for(int i = 0;i < 10;i++)
{
Random1.Numbers[i] = columThree[i];
cout << Random1.Numbers[i] << endl;
};
break;
}
}
run ++;
};
我有一个cout
<< Random1.Numbers[i] << endl;
来检查数字是否保存到Random1.Numbers
中,并且输出是Output
但是,当我尝试在此处显示对象时,问题就来了
cout << Random1;
cout << Random2;
cout << Random3;
调用重载函数,它也是一个 friend 函数
friend ostream &operator<<( ostream &output,const Random & Random1);
ostream &operator<<( ostream &output,const Random & Random1)
{
for(int i = 0;i<10;i++)
{
cout << Random1.Numbers[i] << " ";
}
cout << endl << Random1.NrHighest << endl << Random1.NrLowest << endl << Random1.Index << endl << Random1.IndexH << endl << Random1.IndexL << endl;
return output;
};
我在这里设置了Defauts值
Random()
{
Numbers = {0,0,0,0,0,0,0,0,0,0};
NrHighest = 0;
NrLowest = 0;
Index = 0;
IndexH = 0;
IndexL = 0;
};
这里不是重载值,而是重载运算符的输出