首页 > 编程 > C++ > 正文

C++之操作符重载

2019-11-08 02:44:52
字体:
来源:转载
供稿:网友

1.所谓重载,就是赋予其新的意义。函数可以重载,操作符也可以重载。操作符的重载给我们的编程带来了很大的便利,因为操作符只能对基本的数据类型进行操作,而对用户自定义的类等数据结构类型不支持。因此只能对其操作符进行重载之后,才能更加方便地操作我们自定义的类对象等数据类型。但是值得注意的是并不是C++中的所有运算符都可以进行操作。下面这些操作符就不可以:

. 成员访问运算符?: 条件运算符(三目运算符)* 成员指针访问限定符sizeof 求对象长度操作符

2.重载要注意的一些特征: (1) C++不允许用户重新定义新的运算符,只能对已经存在的操作符号进行重载; (2) 重载不能改变操作符的优先级别; (3) 重载不能改变运算符的运算对象(即就是操作数)的个数,即三目运算符仍然需要三个运算对象,双目运算符需要两个运算对象等。 (4) 重载不能改变运算符的结合性等。

3.运算符的重载实质上是函数的重载,是通过定义函数来实现的。运算符重载函数不仅可以作为类的成员函数,还可以作为全局函数。但是这里有两个特殊的操作符是不能作为成员函数的,那就是<<(流插入运算符)和>>(流提取运算符)。重载运算符的函数的一般格式如下:

函数类型 Operator 运算符名称(形参表) { 对运算符的重载处理 }

重载操作符 + - >> <<

#include <iostream>using namespace std;class Complex { //重载操作符>> friend istream &operator>>(istream &in, Complex &c); //重载操作符<< friend ostream &operator<<(ostream &out,Complex &c); //重载操作符- 通过全局函数的形式 friend Complex operator-(const Complex &c1,const Complex &c2); public: Complex(); //带参数的构造函数 Complex(int real,int imag); //重载操作符+ Complex operator+(const Complex &c); PRivate: int m_real; int m_imag; };Complex::Complex() { this->m_imag=0; this->m_real=0; }Complex::Complex(int real,int imag) { this->m_real=real; this->m_imag=imag; }Complex Complex::operator+(const Complex &c) { Complex b; b.m_real=this->m_real+c.m_real; b.m_imag=this->m_imag+c.m_imag; return b; }Complex operator-(const Complex &c1,const Complex &c2) { Complex c; c.m_real=c1.m_real+c2.m_real; c.m_imag=c1.m_imag+c1.m_imag; return c; } ostream &operator<<(ostream &out,Complex &c) //cout<<t1<<t2; { out<<"("<<c.m_real<<","<<c.m_imag<<"i)"<<endl; return out; } istream &operator>>(istream &in,Complex &c2) { in>>c2.m_real>>c2.m_imag; return in; }int main(void) { Complex c1; Complex c2; Complex c3; cin>>c1>>c2; c3=c1-c2; cout<<c3; system ("pause"); return 0; }

重载操作符:++(自增运算符) 和 –(自减运算符);这里又有前置++和后置++与前置–和后置–;操作符前置和后置的不同点是:操作符的后置中的括号里多了一个Int数据类型,当然这个int数据类型没有其他的作用,仅仅是用来区别操作符是前置运算还是后置运算,如

数据类型 operator ++() //++i 前置++ 数据类型 operator ++(int) //i++ 后置++

未完待续···············


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选