重载>>时未获得预期值。我在这里做错了什么?
Not getting the expected value while overloading >>. What am I doing wrong here?
我是C++的初学者,正在学习它。我现在正在研究运算符重载。在下面的代码中,我重载了>>以获得类值作为输入。但是,我无法像构造函数中描述的那样转换值。当它被转换为构造函数内部的编码时,有什么方法可以做吗。以下是我的代码:
#include <iostream>
using namespace std;
class Time
{
private:
int hour;
int minute;
int second;
public:
Time()
{
Time(0,0,0);
}
Time(int hh, int mm, int ss)
{
second = ss%60;
mm +=ss/60;
minute = mm%60;
hh +=mm/60;
hour = hh;
}
friend istream& operator>>(istream &in, Time &t1);
int GetHour() { return hour; }
int GetMinute() { return minute; }
int GetSecond() { return second; }
};
istream& operator >>(istream &in, Time &tm)
{
in >> tm.hour;
in >> tm.minute;
in >> tm.second;
return in;
}
int main()
{
using namespace std;
Time tm;
cin >> tm;
cout << tm.GetHour() << ":" << tm.GetMinute() << ":" << tm.GetSecond();
return 0;
}
在上面的例子中,无论我输入什么值,都会作为输出而不是构造函数中的语句打印出来。
默认情况下,您正在构造tm
,然后使用重载运算符填充其中的字段。您的3参数构造函数不会被调用。
相关文章:
- 努力将整数转换为链表。不知道我在这里做错了什么
- 我可以在这里替换什么,因为我不能在 C# 中使用隐式变量的 lambda 函数?
- 当我从下面的代码中删除关键字 virtual 时,它可以正常工作,否则会出现错误。在这里"virtual"字的意义是什么?
- File.cpp.o:OpenPose 标志 CMakeFiles/.. 的多重定义/main.cpp.o:首先在这里定
- 为什么thread_local变量在这里从未初始化?
- 为什么我必须在这里使用dynamic_cast
- 在这里,当我们比较 if(vc[i]==vc1[i]) 时,它是向量数组. 实际上比较的值是多少,
- 我正在尝试使用 while 循环从字符串中删除字母,直到没有字母。我在这里做错了什么?
- 为什么 C++20 中的 [[可能]] 属性在这里引发警告?
- 我在这里正确传递参数了吗?
- 为什么gmp会在这里与"invalid next size"重新定位一起崩溃?
- 移动语义在这里如何工作?
- 如何在这里循环运行?
- 为什么枚举变量在这里是右值?
- 我的C++合并排序代码不起作用。我在这里错过了什么?
- 试图美化这个Arduino代码[初学者在这里]
- 复制交换习惯用法-我们可以在这里使用动态强制转换操作吗
- 在这里使用删除运算符是否正确,我很困惑
- 如何使用模板生成整数序列在这里工作
- 为什么sizeof函数在这里不能正常工作