C++ 输入运算符重载

标签 c++ class operator-overloading inputstream

我试图在我创建的 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;
}

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

关于C++ 输入运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14358307/

相关文章:

c++ - std::lower_bound 中使用的比较运算符

c++ - std::map 中的线程安全

c++ - 从另一个 Nan::ObjectWrap 返回一个 Nan::ObjectWrap

python - 试图理解类和对象如何相互交互 - python

java - 列出类的所有字段,如果它们与所需类型匹配,则将它们放入列表中

C++ 运算符重载输入运算符 >> 以类外的对象作为成员

c++ - 3D 中线和三角形的交点

c++ - template<typename T> using L = T(*)(T); 中的 (*) 是什么意思?

python - 派生类重载时调用基类方法

c++ - 在 C++ 中重载运算符->