(0)基础知识
一般格式:函数类型
operator 运算符名称
(形参表)
//相当于函数名
{
对运算符的重载处理;
}
重载的运算符必须和用户定义的自定义类型的对象一起使用,其参数应至少有一个是类对象
(1)运算符重载的作用
1.可以提高代码的可读性
2.体现了C++的可扩展性
(2)运算符重载的实现
1.成员函数重载
2.友元函数重载
(3)不能被重载的运算符
1.作用域解析运算符
::
2.条件运算符
?:
3.直接成员访问运算符
.
4.类成员指针引用的运算符
.*
5.sizeof运算符
sizeof
(4)成员函数运算符和友元函数运算符的选择
1.一般
单目运算符
最好重载为
类的成员函数
双目运算符
最好重载为
类的友元函数
2.=、()、[ ]、->这四个双目运算符不能重载为类的友元函数
3.类型转换运算符只能以成员函数方式重载
4.流运算符只能以友元的方式重载
(5)++运算符重载示例
/******头文件****************
#ifndef _TIME_H_
#define _TIME_H_
class Time
{
public:
Time();
Time(int m,int s);
Time operator++();
Time operator++(int);
void display();
private:
int minute_;
int sec_;
};
#endif
#include <iostream>
#include "time.h"
using namespace std;
Time :: Time()
{
minute_ = 0;
sec_ = 0;
}
Time :: Time(int m,int s) : minute_(m),sec_(s)
{
}
Time Time :: operator++()
{
if(++sec_ >= 60)
{
sec_ = 0;
++minute_;
}
return *this;
}
/************time.cpp文件****************
Time Time :: operator++(int)
{
Time temp(*this);
sec_++;
if(sec_ >= 60)
{
sec_ = 0;
minute_++;
}
return temp;
}
void Time :: display()
{
cout << minute_ << ":" << sec_ << endl;
}
/****************main.cpp**********************
#include <iostream>
#include "time.h"
using namespace std;
int main()
{
Time t1(34,59);
Time t2;
cout << "t1 ";
t1.display();
++t1;
cout << "t1 ";
t1.display();
t2 = t1++;
cout << "t1 ";
t1.display();
cout << "t2 ";
t2.display();
return 0;
}
因为“++”(和“--”)运算符有两种使用方式,前置自增运算符和后置自增运算符,但他们的作用是不一样的,C++中约定,如果在自增(自减)运算符重载函数中,增加一个int型形参,就是后置自增(自减运算符),先使用后自加的那种,但形参int并不起什么实质作用,只起到一个占位符的作用