4

我正在尝试在我创建的 UserLogin 类上重载输入运算符。不会引发编译时错误,但也不会设置值。

一切都运行了,但 ul 的内容仍然存在: string id is sally 登录时间为 00:00 注销时间为 00:00

入口点

#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");
}

用户登录.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) {};
};

用户登录.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;
}
4

3 回答 3

11

你的定义operator>>是错误的。您需要user通过非常量引用传递参数,并摆脱强制转换:

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

    return input;
}

演员表使您读入一个临时文件,然后立即将其丢弃。

于 2013-01-16T12:22:43.223 回答
0
input >> (type) var;

错了,不要这样做。做简单

input >> var;
于 2013-01-16T12:23:24.940 回答
-2
#ifndef STRING_H
#define STRING_H

#include <iostream>
using namespace std;

class String{
    friend ostream &operator<<(ostream&,const String & );


    friend istream &operator>>(istream&,String & );

public:
    String(const char[] = "0");
    void set(const char[]);
    const char * get() const;
    int length();

    /*void bubbleSort(char,int);
    int binSearch(char,char,int);

    bool operator==(const String&);
    const String &operator=(const String &);
    int &operator+(String );*/

private:
        const char *myPtr;
    int length1;

};
#endif
于 2013-11-29T07:45:35.480 回答