1.重载操作符
作用:主要是为解决同一类型的数据方便进行计算,例如在没有重载操作符之前我们将两个数组的相加可能要采用这样的方式才可以:
for( i = 0 ;i << Max; i++)
{
sum[i] = a[i] + b[i];
}
但是我们的目标是设想在其他的数据类型当中像基本数据类型那样子相加减,例如 int a + b方式;为此我们选用重载操作符方法;
使得在数组,结构体,类当中依然可以选用像int类型相加减的形式。
2.重载实例
头文件
#ifndef MYTIME_H
#define MYTIME_H
class Time
{
private:
int hours;
int minutes;
public:
Time();
Time (int h,int m = 0);
~Time();
void AddMin(int m);
void AddHr(int h);
void Reset(int h = 0,int m = 0);
Time operator+ (const Time & t) const;
void Show() const;
};
#endif
类的cpp文件
#include"mytime.h"
#include
Time::Time()
{
hours = minutes = 0;
}
Time::Time(int h,int m)
{
hours = h;
minutes = m;
}
Time::~Time()
{
}
void Time::AddMin(int m)
{
minutes += m;
hours += minutes / 60;
minutes %= 60;
}
void Time::AddHr(int h)
{
hours += h;
}
void Time::Reset(int h,int m)
{
hours = h;
minutes = m;
}
Time Time::operator+ (const Time & t)const
{
Time sum;
sum.minutes = minutes + t.minutes;
sum.hours = hours + t.hours + sum.minutes / 60;
sum.minutes %= 60;
return sum;
}
void Time::Show()const
{
std::cout << hours << "hours, " << minutes << “minutes”;
}
main.cpp
#include
#include “mytime.h”
int main()
{
using std::cout;
using std::endl;
Time plannig; //调用默认构造函数
Time code(2,40);
Time fixing(5,55);
Time total;
cout << "planning time = ";
plannig.Show();
cout << endl;
cout << "coding time = ";
code.Show();
cout << endl;
cout << "fixing time = ";
fixing.Show();
cout << endl;
total = code + fixing;
cout << "code + fixing = ";
total.Show();
cout << endl;
Time morefixing(3,28);
cout << "more fixing time = ";
morefixing.Show();
cout << endl;
total = morefixing.operator+(total);
cout << "morefixing.operator + (total) = ";
total.Show();
cout << endl;
return 0;
}
3.重载限制
3.1不能重载Cpp不存在的操作符,例如@;
3.2重载后的操作符必须至少有一个操作符是用户自定义的类型。
3.3不能违反违反操作符原来的句法规则。
4.友元函数
根据前面类的知识,我们知道访问类的私有部分数据只能通过公有函数,现在提供了另外一种能访问私有数据的方式,友元函数接下来要介绍的内容。
4.1创建友元
在类声明时在原型前加上friend;
注意:1虽然友元函数是在类声明中声明的,但它不是成员函数,不能使用成员操作符调用。
2具有成员函数的访问权限。