C++输入运算符过载
C++ Input 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");
}
用户登录.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
相关文章:
- 重载运算符>>() 表示未知的输入长度/结构
- 在C++中重载输入/输出运算符
- 如何使用运算符>>在自定义字符串中输入多个单词?
- 使用函数重载输入运算符
- 在函数中使用运算符重载,在 c++ 中使用 const 类型输入参数
- 重载输入 (>>) 运算符以获取枚举字符串
- c++中重载输入运算符的问题
- 处理输入流运算符>>中的无效输入
- 如何将重载>>运算符中输入的值插入到资源库
- 使用运算符将分隔的输入分隔>>变量
- 如何输入和输出方括号运算符 []
- 流输入运算符导致分段错误与 clang 但适用于 gcc
- 字符串流运算符输入失败
- 动态内存分配和输入(流)运算符C++
- 重载>>运算符未在输入上设置属性
- 输入迭代器 - 星号和后缀运算符
- 用户输入逻辑运算符符号或数字,如果输入字符或字符串则无效
- 是否可以使用条件运算符将输入流传递给函数?
- C++ 重载运算符>>(输入)不会更改原始运算符
- 与使用运算符重载 C++ 的运算符<<输入输出不匹配