1

首先我试图创建一个文件并写入它,它不允许我使用“<<”来写入文件,第二部分我试图从文件中读取数据,但我不确定这是正确的方法,因为我想将数据保存到对象中,以便稍后在程序中使用这些对象。非常感谢任何帮助或建议。提前致谢

void Employee::writeData(ofstream&)
{
  Employee joe(37," ""Joe Brown"," ""123 Main ST"," ""123-6788", 45, 10.00);
  Employee sam(21,"\nSam Jones", "\n 45 East State", "\n661-9000",30,12.00);
  Employee mary(15, "\nMary Smith","\n12 High Street","\n401-8900",40, 15.00);

  ofstream outputStream;
  outputStream.open("theDatafile.txt");
  outputStream << joe << endl << sam << endl << mary << endl;
  //it says that no operator "<<"matches this operands, operands types are std::ofstream<<employee
  outputStream.close();
  cout<<"The file has been created"<<endl;
}

void Employee::readData(ifstream&)
{
  //here im trying to open the file created and read the data from it, but I'm strugguling to figure out how to read the data and save it into de class objects.
  string joe;
  string sam;
  string mary;

  ifstream inputStream;
  inputStream.open("theDatafile.txt");
  getline(inputStream, joe);
  getline(inputStream, sam);
  getline(inputStream, mary);
  inputStream.close();
}
4

1 回答 1

3

您收到的错误是因为您需要为员工类定义输出运算符。

ostream& operator<<(ostream& _os, const Employee& _e) {
  //do all the output as necessary: _os << _e.variable;
}

最好也实现输入运算符:

istream& operator>>(istream& _is, Employee& _e) {
  //get all the data: _is >> _e.variable;
}

您应该为您的 Employee 类创建这些友元函数:

class Employee {
  public:
    //....
    friend ostream& operator<<(ostream& _os, const Employee& _e);
    friend istream& operator>>(istream& _is, Employee& _e);
    //....
}
于 2013-10-21T21:30:39.240 回答