use*_*364 4 c++ class inputstream operator-overloading
我正在尝试在我创建的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");
}
Run Code Online (Sandbox Code Playgroud)
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) {};
};
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
Rei*_*ica 11
你的定义operator>>是错误的.你需要user通过非const引用传递参数,并摆脱强制转换:
istream &operator >>( istream &input, UserLogin &user )
{
input >> user.id;
input >> user.login;
input >> user.logout;
return input;
}
Run Code Online (Sandbox Code Playgroud)
演员表会让你读到一个临时的,然后立即丢弃.
| 归档时间: |
|
| 查看次数: |
11495 次 |
| 最近记录: |