重载>>运算符未在输入上设置属性
Overloading >> operator is not setting attributes on input
我是C++新手,并试图通过重载>> 运算符从 cin 读入我的对象。但是,输入后,我创建的对象保持不变。
页眉:
class Duration {
private:
int hours, mins, secs;
public:
Duration();
Duration(int hours, int mins, int secs);
};
inline Duration::Duration() {
this->hours = 0;
this->mins = 0;
this->secs = 0;
}
inline Duration::Duration(int hours, int mins, int secs) {
this->hours = hours;
this->mins = mins;
this->secs = secs;
}
inline istream& operator>>(istream& is, Duration &d) {
char c1, c2;
int hours, mins, secs;
if (is >> hours >> c1 >> mins >> c2 >> secs) {
if (c1 == c2 == ':') {
d = Duration(hours, mins, secs);
}
else {
is.clear(ios_base::failbit);
}
}
return is;
}
inline ostream& operator<<(ostream& os, const Duration &d) {
return os << d.getHours() << ":"
<< d.getMins() << ":"
<< d.getSecs();
}
和我的主要:
int main(int argc, char** argv) {
Duration test;
cin >> test;
cout << test << endl;
return EXIT_SUCCESS;
}
我很确定我已经在需要时包含了所有"通过引用"指示,我不确定我做错了什么。无论我在运行程序时输入什么,生成的Duration test
都具有值 0:0:0
。
if (c1 == c2 == ':')
是所指出的问题,评估true == ':'
哪个当然等于false
。我用if (c1 == c2 && c2 == ':')
修复了它(不确定是否最有效,但现在肯定按预期工作(。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 在C++/Linux中设置单调时钟的一些技巧
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 嵌套在类中时无法设置成员数据
- 需要帮助设置在C++中使用的Potrace
- 如何在自删除后将对象设置为nullptr
- 将指针设置为"nullptr"并不能防止双重删除?
- 如何在Ubuntu中使用cmake设置qt4
- ld:bind_at_load和-bitcode_bundle(Xcode设置ENABLE_bitcode=YES)不能
- 如何在boost beast http请求中设置http头
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 为什么文件名被设置为一个点,而不是在读取矢量中的文件名时
- 如何在24位SDL_Surface上设置像素的颜色
- std::设置自定义比较器
- 如何设置一个范围来提取我想要获得的信息
- 如何在C/C++中用FD_set Unix设置套接字文件描述符
- EASTL矢量<向量<int>>连续的
- 通过选项卡的文本设置QTabWidget顺序
- 将特征矩阵的向量设置为0