这是我的作业,我不知道为什么输出这个数字。
这是程序
#include <iostream>
#include <vector>
using namespace std;
class Employee
{
protected:
long empId;
string empName;
string email;
public:
Employee(){}
Employee(long i, string n){empName = n; empId = i; email = "Unknown";}
friend istream& operator>>(istream& in, const Employee& emp);
friend ostream& operator<<(ostream& out, const Employee& theQ);
};
class Student
{
protected:
long stId;
int year;
string email;
string schoolName;
public:
Student(){}
Student(long i, int y, string sn){stId = i; year = y; email = "Unknown"; schoolName = sn;}
friend istream& operator>>(istream& in, const Student& stu);
};
template <class T>
class Queue {
vector<T> theQ;
public:
void Push(T item)
{
theQ.push_back(item);
}
T Pop() {
theQ.pop_back();
}
void ReadAnItem()
{
T item;
cout << "Enter the data please." << endl;
cin >> item;
Push(item);
}
void PrintQ() {
cout<< "The content of the array is as follows: " << endl;
for (int i=0; i< theQ.size(); i++)
cout << theQ[i] << endl;
}
};
ostream& operator<<(ostream& out, const Employee& emp){
out << emp.empId << endl;
out << emp.empName << endl;
out << emp.email << endl;
return out;
}
istream& operator>>(istream& in, const Employee& emp) {
long i;
string n;
cout << "Enter employee ID: ";
in >> i;
cout << "Enter employee name: ";
in >> n;
Employee(i, n);
return in;
}
istream& operator>>(istream& in, const Student& stu) {
long i;
int y;
string sn;
cout << "Enter student ID: ";
in >> i;
cout << "Enter student year: ";
in >> y;
cout << "Enter student school name: ";
in >> sn;
Student(i, y, sn);
return in;
}
int main() {
Queue<Employee> emp1;
emp1.ReadAnItem();
Queue<Student> stu1;
stu1.ReadAnItem();
emp1.PrintQ();
return 0;
}
输出
阵列的内容如下:
140734799804080
输出数据似乎工作正常。我有一种感觉错误来自操作员的重载。我不太确定,我现在已经困惑了几个小时。
我哪里错了?
答案 0 :(得分:4)
问题似乎出现在operator>>
功能中。您没有为emp
参数指定任何内容。尝试:
istream& operator>>(istream& in, Employee& emp) {
...
emp = Employee(i, n);
return in;
}
实际返回刚构建的数据需要赋值emp
。我还必须从您的声明中删除const
,因为您需要能够写入emp
。