繁体   English   中英

C ++程序输出一个非常大的数字而不是对象

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM