C++输入运算符过载

C++ Input Operator Overloading

本文关键字:运算符 输入 C++      更新时间:2023-10-16

我正试图在我创建的UserLogin类上重载输入运算符。没有抛出编译时错误,但是也没有设置值。

一切都在运行,但ul的内容仍然存在:字符串id是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;
}

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

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

强制转换导致您读入一个临时文件,然后立即丢弃该临时文件。

input >> (type) var;

是错误的,不要这样做。做简单的

input >> var;
#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