重载 << 时出错。我在这里做错了什么?
Error while overloading <<. What am I doing wrong here?
我正在学习 C++,并且正在研究重载 <<。我正在使用以下代码打印 class 的时间。它似乎与友元功能一起工作,但是当我在没有友元的情况下使用时,它似乎导致了错误“运算符<<不匹配”。我在这里做错了什么?下面是我的代码:
#include <iostream>
using namespace std;
class Time
{
private:
int hour;
int minute;
int second;
public:
Time(int hh, int mm, int ss)
{
second = ss%60;
mm +=ss/60;
minute = mm%60;
hh +=mm/60;
hour = hh;
}
ostream& operator<<(ostream &out); //overloading << function declaration
};
ostream& Time::operator <<(ostream &out) // overloading << function definition
{
out << "Time - " << hour << ":" << minute << ":" << second;
return out;
}
int main()
{
using namespace std;
Time tm(10,36,60);
cout << tm;
return 0;
}
函数
ostream& operator<<(ostream &out);
定义 <<
使得 LHS 是一个 Time
对象而 RHS 是一个 std::ostream
对象。
可用作:
Time tm(10,36,60);
tm << cout;
不如
cout << tm;
使用
cout << tm;
您需要定义一个 LHS 类型为 std::ostream
的函数。因此,它不能是 Time
.
的成员函数
将函数声明为:
friend ostream& operator<<(ostream &out, Time const& ti);
并据此实施。
当您有成员运算符重载时,运算符的左侧是该 class 的对象。那么您的会员:
ostream& operator<<(ostream &out);
实际上会匹配用法:
tm << cout
但不是 cout << tm
。
要解决此问题,您应该使用非成员函数。我的首选方式是:
// not inside a class definition
ostream &operator<<(ostream &os, Time const &tm)
{
// output using public methods of tm
return os;
}
然而,另一种常用技术是使用友元函数:
// Inside Time's class definition
friend ostream &operator<<(ostream &os, Time const &tm)
{
// output using private members of tm
return os;
}
请注意,即使后者出现在 class 定义中,它实际上也不是成员函数。 friend
关键字使它如此。
我正在学习 C++,并且正在研究重载 <<。我正在使用以下代码打印 class 的时间。它似乎与友元功能一起工作,但是当我在没有友元的情况下使用时,它似乎导致了错误“运算符<<不匹配”。我在这里做错了什么?下面是我的代码:
#include <iostream>
using namespace std;
class Time
{
private:
int hour;
int minute;
int second;
public:
Time(int hh, int mm, int ss)
{
second = ss%60;
mm +=ss/60;
minute = mm%60;
hh +=mm/60;
hour = hh;
}
ostream& operator<<(ostream &out); //overloading << function declaration
};
ostream& Time::operator <<(ostream &out) // overloading << function definition
{
out << "Time - " << hour << ":" << minute << ":" << second;
return out;
}
int main()
{
using namespace std;
Time tm(10,36,60);
cout << tm;
return 0;
}
函数
ostream& operator<<(ostream &out);
定义 <<
使得 LHS 是一个 Time
对象而 RHS 是一个 std::ostream
对象。
可用作:
Time tm(10,36,60);
tm << cout;
不如
cout << tm;
使用
cout << tm;
您需要定义一个 LHS 类型为 std::ostream
的函数。因此,它不能是 Time
.
将函数声明为:
friend ostream& operator<<(ostream &out, Time const& ti);
并据此实施。
当您有成员运算符重载时,运算符的左侧是该 class 的对象。那么您的会员:
ostream& operator<<(ostream &out);
实际上会匹配用法:
tm << cout
但不是 cout << tm
。
要解决此问题,您应该使用非成员函数。我的首选方式是:
// not inside a class definition
ostream &operator<<(ostream &os, Time const &tm)
{
// output using public methods of tm
return os;
}
然而,另一种常用技术是使用友元函数:
// Inside Time's class definition
friend ostream &operator<<(ostream &os, Time const &tm)
{
// output using private members of tm
return os;
}
请注意,即使后者出现在 class 定义中,它实际上也不是成员函数。 friend
关键字使它如此。