1 自增运算符++ 自减运算符-- 有前置/后置之分,为了区分所重载的是前置运算符还是后置运算符,C++规定:
前置运算符作为一元运算符重载
重载为成员函数:
T& operator++();
T& operator--();
重载为全局函数:
T1& operator++(T2);
T1& operator--(T2);
后置运算符作为二元运算符重载,多写一个没用的参数:
重载为成员函数:
T operator++(int);
T operator--(int);
重载为全局函数:
T1 operator++(T2, int);
T1 operator--(T2, int);
但是在没有后置运算符重载而有前置运算符重载的情况下,在vs中,obj++也调用前置重载,而dev则令obj++编译出错。
2 例子(见本工程zizengjian.cpp) 好好理解 非常重要
zizengjian.cpp
//
// 自增、自减重载运算符实例
//
#include <iostream>
#include "CDemo.h"
using namespace std;
int main()
{
// 一个对象成员变量 存储5
CDemo d(5);
// 重载后置++运算符 (使用成员函数重载,也可使用全局函数重载)
cout << (d++) << ",";
// 重载类型转换运算符(使用成员函数重载,也可使用全局函数重载)
cout << d << ",";
// 重载前置++运算符(使用成员函数重载,也可使用全局函数重载)
cout << (++d) << ",";
cout << d << endl;
// 重载后置--运算符(使用全局函数重载,也可使用成员函数重载)
cout << (d--) << ",";
cout << d << ",";
// 重载前置--运算符(使用全局函数重载,也可使用成员函数重载)
cout << (--d) << ",";
cout << d << endl;
return 0;
}
CDemo.h
/**
* 需要编写:
*
* */
#ifndef BEIDALESSON1_CDEMO_H
#define BEIDALESSON1_CDEMO_H
class CDemo {
private:
int n;
public:
// 构造函数 也可以使用参数列表进行初始化,使用了缺省参数。
CDemo(int i = 0);
// 重载前置++运算符 一元运算符
//问题:为什么返回值为CDemo&? 答案:C++原生的++运算符中 ++a表达式返回值就是a的引用,因此重载++的时候尽量维持这种属性。
//可以执行一下(++a) = 1;然后输出a=1,则可以证明++a的返回值为a的引用。
//不可以执行(a++)= 1 原因:在C++中后置运算符并没有返回它所操作的这个变量的引用,它返回的时a在加1之前的值的临时变量
CDemo& operator++();
// 重载后置++运算符 二元运算符
CDemo operator++(int);
// 重载类型转换运算符 一元运算符
operator int();
// 对全局变量进行友元的声明
friend CDemo& operator--(CDemo&); // 前置--运算符重载
friend CDemo& operator--(CDemo&, int); // 后置--运算符重载
};
#endif //BEIDALESSON1_CDEMO_H
CDemo.cpp
//
// 此例子可以看出前置++ 前置-- 运算效率高于后置++ 后置--
//
#include "CDemo.h"
// 构造函数
CDemo::CDemo(int i) {
n = i;
}
// 重载前置++运算符
CDemo& CDemo::operator++() {
++n;
return *this; // *this指的就是++刚才作用的那个对象 ++s即为s.operator++() 返回值为s的引用 符合原生态++的特性
}
// 重载后置++运算符 多了一个没用的参数k; 返回值是一个对象 s++等价于s.operator++(0);
CDemo CDemo::operator++(int k) {
CDemo tmp(*this); // 记录修改前的对象 使用复制构造函数初始化tmp
n++;
return tmp; //返回修改前的对象
}
// 重载类型转换运算符
CDemo::operator int() {
return n;
}
// 重载前置--运算符 s++;等价于operator--(s);
CDemo& operator--(CDemo& d) {
d.n--;
return d;
}
// 重载后置--运算符 s--;等价于operator--(s, 0);
CDemo& operator--(CDemo & d, int) {
CDemo tmp(d); // 使用复制构造函数初始化tmp
d.n --;
return tmp;
}
3 运算符重载的注意事项
(1)C++不允许定义新的运算符;
(2)重载后的运算符的含义应该符合日常习惯;
complex_a + complex_b
word_a > word_b
date_b = date_a +n
(3)运算符重载不改变运算符的优先级
(4)以下运算符不能被重载: “.” “.*” “::” “?:” sizeof
(5)重载运算符() [] -> 或者赋值运算符=时,运算符重载函数必须声明为类的成员函数。