개체 배열이 개인 변수 인 클래스에 대한 읽기 및 인쇄 기능을 정의해야합니다. 텍스트 파일에서 객체를 읽고 화면에 인쇄해야합니다. 이렇게하려면 < < 및 >> 연산자를 오버로드해야합니다. 배열에 저장된 정보를 읽고 인쇄하는 데 루프를 사용해야한다는 것을 알고 있지만이를 수행하는 방법을 모르겠습니다. 저의 강사는 기본적으로 함수 프로토 타입 인 스켈레톤 코드와 내가 지켜야 할 주요 기능을 제공했습니다. 나는 이것을 사용하여이 정확한 시나리오를 수행 했으므로 public struct와 어떻게 작동하는지 이해하지만 class의 private 변수가 나를 트립시킵니다.텍스트 파일에서 I/O 오버로드 및 읽기
class EmployeeList {
public:
//Constructors
EmployeeList();
EmployeeList(istream&);
//Accessors
bool isEmpty() const;
bool isFull() const;
int size() const; //Number of employees in list
Employee item(int i) const; //i'th employee
//Mutators
void setItem(int i,const Employee& e);
//I/O functions, sets the i'th emplyee to e
void read(istream&);
void print(ostream&) const;
private:
enum {MAXSIZE = 100};
Employee list[MAXSIZE];
int count; //Number of employees in the current list
};
EmployeeList::EmployeeList() {
count = 0;
}
EmployeeList::EmployeeList(istream& in) {
//list[MAXSIZE] = in;
}
bool EmployeeList::isEmpty() const {
return (count == 0);
}
bool EmployeeList::isFull() const {
return (count == MAXSIZE);
}
int EmployeeList::size() const {
return count;
}
Employee EmployeeList::item(int i) const {
}
void EmployeeList::setItem(int i, const Employee& e) {
}
void EmployeeList::read(istream& in) {
Employee tempList;
while (in >> tempList) {
}
}
void EmployeeList::print(ostream& out) const {
for (int i=0; i < size(); i++) {
}
cout << out;
}
위의 부분은 EmployeeList 클래스이며 아래 부분은 오버로드 함수입니다. 주석 처리 된 부분은 생각할 수 있지만 생각하지 못한 아이디어입니다.
istream& operator>>(istream& in, EmployeeList& l) {
l.read(in);
return in;
}
ostream& operator<<(ostream& out, const EmployeeList& l) {
l.print(out);
return out;
}
다음은 우리에게 주어진 주요 기능입니다.
int main() {
authorInfo();
ifstream infile("a1in.txt");
if(!infile) {
cout << "file 'alin.txt' not found.";
return EXIT_FAILURE;
}
EmployeeList theList(infile);
cout << endl;
cout << theList.size() << " employees read:\n" << theList << endl;
process(theList);
return EXIT_SUCCESS;
}
누군가가 올바른 방향으로 나를 조종 할 수 있기를 바랍니다. 더 많은 코드가 필요한 경우 알려 주시기 바랍니다. 감사!
EDIT : 직원 읽고 인쇄 기능 :
void Employee::read(istream& in) {
in >> name >> id >> salary;
}
void Employee::print(ostream& out) const {
out << getName() <<" "<< getID() <<" "<< getSalary() << endl;
}
직원 오버로딩 :
istream& operator>>(istream& in, Employee& e) {
e.read(in);
return in;
}
ostream& operator<<(ostream& out, const Employee& e) {
e.print(out);
return out;
}
EDIT 2 업데이트 판독() 함수. 잠시 동안의 줄은 오류가있는 곳입니다.
void EmployeeList::read(istream& in) {
Employee inEmployee;
while (in >> inEmployee && count < MAXSIZE) {
list[count] = inEmployee;
count++;
}
}
편집 3 : 여기까지 제가 가지고있는 print() 함수가 있습니다. 실제로 인쇄하지만 파일에서 정보가 아니라 기본 생성자 정보를 얻습니다. 읽기 또는 인쇄 기능 문제입니까? 나는 아직도 읽기 기능을 생각하고있다.
void EmployeeList::print(ostream& out) const {
cout << endl;
for (int i=0; i < count; i++) {
out << list[count];
}
}
왜 개인 변수가 당신을 트립합니까? 공개 섹션에서 필요한 정보는 모두 한 눈에 볼 수 있습니다. – BugFinder
이름, ID 또는 급여의 공백은 Employee :: read를 깨뜨릴 것입니다. –