这是我的作业,我不知道为什么要输出这个数字。
这是程序
#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;
}
和输出
The content of the array is as follows:
140734799804080
输出数据似乎工作正常。我感觉错误来自运算符重载。我不太确定,我已经困惑了几个小时了。
我哪里错了?
最佳答案
问题似乎出在您的 operator>>
函数中。您没有为 emp
参数分配任何内容。尝试:
istream& operator>>(istream& in, Employee& emp) {
...
emp = Employee(i, n);
return in;
}
emp
的赋值需要实际返回您刚刚构造的数据。我还必须从您的声明中删除 const
,因为您需要能够写入 emp
。
关于C++ 程序输出一个非常大的数字而不是对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46415648/