运算符重载
- 常见重载运算符及返回值
常见的重载运算符有:
class Time
{
public:
const Time operator+(const Time& t) const; //加减乘除返回类型为 const Time
Time& operator=(const Time& t); //赋值运算符返回类型为 Time&,要注意判断 &t==this
Time& operator++(); //前置++无参数,返回类型为 Time&
Time operator++(int); //后置++有参数int,返回类型为 Time
};
- 友元函数
友元函数不是类的成员函数,但是可以访问类的私有成员。友元函数在类中声明,声明时添加关键字friend,实现时不需要类作用域,不需要friend。常见的友元函数有<<和>>的重载。
class Time
{
public:
//返回类型为ostream&以方便连续输出
friend ostream& operator<<(ostream& os, const Time& t);
};
ostream& operator<<(ostream& os, const Time& t)
{
os<<"我的输出"<<endl;
return os;
}
- 转换函数
类可以通过构造函数将其他类型变量转换为类对象。
可以通过转换函数将类对象转换为其他类型,转换函数格式为 operator typeName (); 声明中无须返回值,但是实现中需要有返回值,typeName 为想要转换成为的类型。
class Time
{
public:
operator int()
{
return int(4);
}
};