ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

七:运算符重载

2020-05-05 17:52:44  阅读:199  来源: 互联网

标签:int Three operator 运算符 ++ 重载


7.1:运算符重载成员函数

     运算符重载:就是对已经有的运算符赋予多重的含义,使用同一个运算符作用于不同类型产生不同的行为。

     运算符重载函数: operator+() operator-() 

示例:

 Complex operator+( Complex om1 , Complex om2  )

 {

 Complex temp;

 temp.real = om1.real + om2.real ;

 temp.imag = om1.image + om2.image;

 return temp;

 }

 

     

 调用: total = com1+com2;

 

C++ 运算符重载的问题

 

(1) C++只能对已经有的C++运算符进行重载,不允许用户自定义新的运算符. 例如**

(2) C++ 不能重载的运算符

 .       成员访问运算符

 .*      成员访问指针

 ::      作用域运算符

 sizeof  长度运算符

 ?:      条件运算符

(3)重载是不能改变操作运算符的个数。

(4)重载不能改变运算符的优先级。

(5)运算符重载函数的参数不能全部是C++预定义的基本数据类型。 

  7.2:前置运算符和后置运算符的重载

a++ ,++a;

C++中编译器通过运算符函数参数表中是否插入关键字 int  来区分这两种方式。

++ob

声明方式: operator ++();

ob++

声明方式: operator++(X &ob, int);

#include<iostream>
using namespace std;

class Three_d{
 private:
  int t1,t2,t3;
 public:
  Three_d( int s1, int s2, int s3 ):t1(s1),t2(s2),t3(s3){};
  void dip();
  Three_d operator++();  //重载前置运算符
  Three_d operator++( int ); //重载后置运算符
};

//声明类的成员函数
void Three_d::dip()
{
    cout<<"  "<<this->t1<<endl;
    cout<<"  "<<this->t2<<endl;
    cout<<"  "<<this->t3<<endl;
}

Three_d Three_d::operator++()
{
   ++this->t1;
   ++this->t2;
   ++this->t3;
   return *this; //返回自增后的对象;
}

Three_d Three_d::operator++(  int )
{
   Three_d temp(*this);
   this->t1++;
   this->t2++;
   this->t3++;
   return temp; //返回自增后的对象;
}
int main( )
{
   Three_d t1(1,2,3),t2(0,0,0);
   cout<<"初始数值--------"<<endl;
   t1.dip();
   t2=++t1;
   cout<<"前置自增--------"<<endl;
   t2.dip();
   t2=t1++;
   cout<<"后置自增--------"<<endl;
   t2.dip();

}  

 

标签:int,Three,operator,运算符,++,重载
来源: https://www.cnblogs.com/love-life-insist/p/12831617.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有