我正在尝试重载 << 运算符并打印出 emp.name

I'm trying to overload << operator and print out emp.name

我正在尝试创建一个链表。我有 3 个 classes - EmployeeListOfEmployeeNodeofEmployee。所有函数都存储在头文件中。

员工class

class Employee {
    friend class NodeofEmployee;
public:
    Employee();
    Employee(string n, double s); 
                
private:
    string name;
    double salary = 0;
};

员工名单class

class ListOfEmployee {
private:
    NodeofEmployee* head;               //getting point to NodeofInt class
        
public:
    ListOfEmployee();                   //constructor
    ~ListOfEmployee();                  //destructor
    void insertAtfront(string, double);         //insert value to the back
    void getSalary(string name);                //prints of value
    int deleteMostRecent();         //delete last value
    void display();
    friend ostream& operator <<(ostream& outputStream, const ListOfEmployee& e);
};

员工节点class

class NodeofEmployee {
    friend class ListOfEmployee;
public:
    NodeofEmployee(int id, string name);
private:
    Employee emp;               
    NodeofEmployee* next;           //the address of the next value     
};

我想重载operator<<,但它不会让我打印出员工姓名和薪水:

ostream& operator <<(ostream& outputStream, const ListOfEmployee& e) {
    NodeofEmployee *newpptr = e.head;
    while (!e.head) {
        outputStream << newpptr;
    }
    
    return outputStream;
}

所以这里(至少)有两个错误

ostream& operator <<(ostream& outputStream, const ListOfEmployee& e) {
    NodeofEmployee *newpptr = e.head;
    while (!e.head) {
        outputStream << newpptr;
    }
    return outputStream; 
}

第一个错误是 newpptr 不是 Employee,而是 NodeofEmployee 指针。要打印 Employee,您需要

        outputStream << newpptr->emp;

第二个错误是,尽管您编写了一个 while 循环,但实际上并没有在列表中循环。 newpptr 在你的循环中永远不会改变,而且循环条件是错误的。我想你想要这样的东西

    NodeofEmployee *newpptr = e.head;
    while (newpptr) {
        outputStream << newpptr->emp;
        newpptr = newpptr->next;
    }

第三个明显的问题是您没有为 Employee 定义 operator<<。所以你需要添加这个

class Employee {
    ...
    friend ostream& operator <<(ostream& outputStream, const Employee& e);
};

在这个最后的 operator<< 中,您将打印姓名和薪水。

    ostream& operator <<(ostream& outputStream, const Employee& e)
    {
        outputStream << e.name << ' ' << e.salary << '\n';
        return outputStream;
    }