Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Input Operator Overloading

I'm trying to overload the input operator on a UserLogin class I've created. No compile-time errors are thrown, however the values are not set either.

Everything runs, but it the content of ul remains: string id is sally Time login is 00:00 Time logout is 00:00

Entry Point

#include <iostream>
#include "UserLogin.h"

using namespace std;

int main() {
    UserLogin ul;

    cout << ul << endl; // xxx 00:00 00:00
    cin >> ul; // sally 23:56 00:02
    cout << ul << endl; // Should show sally 23:56 00:02
                        // Instead, it shows xxx 00:00 00:00 again

    cout << endl;
    system("PAUSE");
}

UserLogin.h

#include <iostream>
#include <string>
#include "Time.h"

using namespace std;

class UserLogin
{
    // Operator Overloaders
    friend ostream &operator <<(ostream &output, const UserLogin user);
    friend istream &operator >>(istream &input, const UserLogin &user);

    private:
        // Private Data Members
        Time login, logout;
        string id;

    public:
        // Public Method Prototypes
        UserLogin() : id("xxx") {};
        UserLogin( string id, Time login, Time logout ) : id(id), login(login), logout(logout) {};
};

UserLogin.cpp

#include "UserLogin.h"

ostream &operator <<( ostream &output, const UserLogin user )
{
    output << setfill(' ');
    output << setw(15) << left << user.id << user.login << " " << user.logout;

    return output;
}

istream &operator >>( istream &input, const UserLogin &user )
{
    input >> ( string ) user.id;
    input >> ( Time ) user.login;
    input >> ( Time ) user.logout;

    return input;
}
like image 238
user1960364 Avatar asked Jan 14 '23 12:01

user1960364


1 Answers

Your definition of operator>> is wrong. You need to pass the user argument by non-const reference, and get rid of the casts:

istream &operator >>( istream &input, UserLogin &user )
{
    input >> user.id;
    input >> user.login;
    input >> user.logout;

    return input;
}

The casts are causing you to read into a temporary, which is then immediately discarded.

like image 140
Angew is no longer proud of SO Avatar answered Jan 21 '23 20:01

Angew is no longer proud of SO