您的位置:首页 > 其它

运算符重载之前置自增运算符和后置自增运算符

2017-12-27 14:23 405 查看
运算符重载是C++多态性的一种体现,运算符的重载对像C++这类面向对象的编程语言编程很有帮助。
今天这里介绍运算符重载里的自增运算符。
我们都知道自增运算符++有两种,一个是前置,一个后置,至于它们什么区别这里不赘述。
那么我们应该如何重置前置自增运算符和后置自增运算符呢?
[返回类型] operator++() ;    //如果参数列表里什么都没有,那么就是重载前置自增运算符
[返回类型] operator++(int) ;    /*如果参数列表里有一个参数,不管是什么类型,那么就是重载后置自增运算符,这个类型是int,double或者是其他都无所谓,它的目的仅仅是告诉编译器这里是有参数的,如果有参数,编译器就知道这里是重载后置运算符。*/
下面是我写的编程例子,注释不多,就是定义一个复数的类型,里面重载了+和前置自增和后置自增。#include<iostream>
using namespace std;
class complex
{
private:
double real,img;
public:
complex(double x=0.0,double y=0.0):real(x),img(y){ }
virtual ~complex(){ }

double read_real()
{
return real;
}

double read_img()
{
return img;
}

void set_real(double t)
{
real=t;
}

void set_img(double t)
{
img=t;
}

complex operator+(const complex& one)
{
complex result(this->real+one.real,this->img+one.img);
return result;
}

complex operator++() //前置自增运算符
{
complex result;
this->real++;
this->img++;
result.set_real(this->real);
result.set_img(this->img); //自增完才赋值

return result;
}

complex operator++(int) //后置自增运算符
{
complex result;
result.set_real(this->real);
result.set_img(this->img); //先赋值再自增
this->real++;
this->img++;

return result;
}
};

int main()
{
complex a(3.2,4.5),b(1.1,2.4);
cout<<"a:"<<a.read_real()<<"+"<<a.read_img()<<"i\n";
cout<<"b:"<<b.read_real()<<"+"<<b.read_img()<<"i\n";

complex c=a+b;
cout<<"c:"<<c.read_real()<<"+"<<c.read_img()<<"i\n";

cout<<"\n\n下面展示前置自增运算符:\n";
a=++c;
cout<<"a:"<<a.read_real()<<"+"<<a.read_img()<<"i\n";
cout<<"c:"<<c.read_real()<<"+"<<c.read_img()<<"i\n";

cout<<"\n\n下面展示后置自增运算符:\n";
a=c++;
cout<<"a:"<<a.read_real()<<"+"<<a.read_img()<<"i\n";
cout<<"c:"<<c.read_real()<<"+"<<c.read_img()<<"i\n";

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: