[英]C++ program outputs a very large number instead of object
這是我的作業,我不知道為什么輸出這個數字。
這是該計划
#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
輸出數據似乎工作正常。 我有一種感覺錯誤來自操作員的重載。 我不太確定,我已經困惑了幾個小時了。
我哪里錯了?
問題似乎出現在您的operator>>
功能中。 你沒有給emp
參數賦值。 嘗試:
istream& operator>>(istream& in, Employee& emp) {
...
emp = Employee(i, n);
return in;
}
對emp
的賦值需要實際返回剛剛構造的數據。 我還必須從你的聲明中刪除const
,因為你需要能夠寫入emp
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.