c++classobjectcompiler-errorsoperand

Operator Overloading Error: no match for 'operator>>'


This is my header file. Im trying to overload the istream operator and use ifstream in my main function to read in a text file with structured data (rows and columns). I am getting the error "[Error] no match for 'operator>>' (operand types are 'std::istringstream {aka std::basic_istringstream}' and 'std::string {aka std::basic_string}') I commented where I am getting the error. My main function is basically empty so far besides The class and object.

#include <iostream>
#include <fstream>
#include <sstream>
#include <string> 
using namespace std;

class Record
{
    private:
        string name;
        int id;
        double rate;
        double hours;
    public: 
        Record();
        Record (string n, int empid, double hourlyRate, double hoursWorked); 
// constructor

        void read_data_from_file();
        double calculate_wage();
        void print_data();

        /* SETTERS AND GETTERS */           
        void set_name (string n);
        string get_name();

        void set_id (int empid);
        int get_id();

        void set_rate (double hourlyRate);
        double get_rate();

        void set_hoursWorked(double hoursWorked);
        double get_hoursWorked();
        /* END OF SETTERS AND GETTERS */

        friend istream& operator >> (istream& is, Record& employee)
        {
            string line;
            getline (is, line);

            istringstream iss(line);

            iss >> employee.get_name(); // where i get error
        }

}; 

Solution

  • You have to change the get_name() to return a non-const reference, like string& get_name(); to get it working/compile. But will look strange.

    What you can do instead is pass the member name directly

    iss >> employee.name;
    

    that's what friends do.

    And don't forget to return the stream is.