C++运算符重载
2016-08-09 16:29
344 查看
C++运算符重载:
重载方法:成员函数重载 | 友元函数重载 |
---|
①、 C++中的运算符除了少数几个之外,全部可以重载,而且只能重载C++中已有的运算符。
②、 重载之后运算符的优先级和结合性都不会改变。
③、 运算符重载是针对新类型数据的实际需要,对原有运算符进行适当的改造。一般来说,重载的功能应当与原有功能相类似,不能改变原运算符的操作对象个数,同时至少要有一个操作对象是自定义类型。
不能重载的运算符只有五个,它们是:
运算符 | 名称 |
---|---|
. | 成员运算符 |
* | 指针运算符 |
:: | 作用域运算符 |
sizeof() | sizeof |
?: | 条件运算符 |
运算符重载为类的成员函数的一般语法形式为:
函数类型 operator 运算符(形参表) { 函数体; }
运算符重载为类的友元函数的一般语法形式为:
friend 函数类型 operator 运算符(形参表) { 函数体; }
其中,函数类型就是运算结果类型;operator是定义运算符重载函数的关键字;运算符是重载的运算符名称。
当运算符重载为类的成员函数时,函数的参数个数比原来的操作个数要少一个;当重载为类的友元函数时,参数个数与原操作数个数相同。原因是重载为类的成员函数时,如果某个对象使用重载了的成员函数,自身的数据可以直接访问,就不需要再放在参数表中进行传递,少了的操作数就是该对象本身。而重载为友元函数时,友元函数对某个对象的数据进行操作,就必须通过该对象的名称来进行,因此使用到的参数都要进行传递,操作数的个数就不会有变化。
运算符重载的主要优点就是允许改变使用于系统内部的运算符的操作方式,以适应用户自定义类型的类似运算。
” -” 单目运算符 “负号重载
“++” 前置,后置运算符重载
“+” 运算符重载
“-” 运算符重载
“<<” 运算符重载(必须使用友元函数进行重载)
“[]” 索引运算符重载(必须使用成员函数进行重载)
Coordinate.h
// // Created by butter on 16-8-5. // #ifndef OPREATOR_COORDINATE_H #define OPREATOR_COORDINATE_H #include <ostream> class Coordinate { friend Coordinate &operator-(Coordinate &c); // friend Coordinate operator+(const Coordinate &c1, const Coordinate &c2); friend std::ostream &operator << (std::ostream & optput, Coordinate & coor); public: Coordinate(); Coordinate(int x, int y); //Coordinate &operator-(); Coordinate &operator++(); Coordinate operator++(int); //标志 Coordinate operator+(const Coordinate &coor); int operator[] (int index); int getX(); int getY(); private: int m_iX; int m_iY; }; #endif //OPREATOR_COORDINATE_H
Coordinate.cpp
// // Created by butter on 16-8-5. // #include "Coordinate.h" #include <ostream> Coordinate::Coordinate() { } Coordinate::Coordinate(int x, int y) { m_iX = x; m_iY = y; } /* Coordinate &Coordinate::operator-(){ m_iX = -m_iX; this->m_iY = -this->m_iY; return *this; } */ int Coordinate::getX() { return m_iX; } int Coordinate::getY(){ return m_iY; } Coordinate &operator-(Coordinate &c){ c.m_iX = -c.m_iX; c.m_iY = -c.m_iY; return c; } Coordinate &Coordinate::operator++() { m_iX++; m_iY++; return * this; } Coordinate Coordinate::operator++(int)//标志 { Coordinate old(*this); this->m_iX++; this->m_iY++; return old; } Coordinate Coordinate::operator+(const Coordinate &coor){ Coordinate tmp; tmp.m_iX = coor.m_iX + this -> m_iX; tmp.m_iY = coor.m_iY + this -> m_iY; return tmp; } /* Coordinate operator+(const Coordinate &c1, const Coordinate &c2){ Coordinate tmp; tmp.m_iX = c1.m_iX + c2.m_iX; tmp.m_iY = c1.m_iY + c2.m_iY; return tmp; } */ std::ostream &operator << (std::ostream & output, Coordinate & coor){ output << coor.m_iX << "," << coor.m_iY; return output; } int Coordinate::operator[] (int index){ if(index == 0) return m_iX; if(index == 1) return m_iY; }