zoukankan      html  css  js  c++  java
  • 七:运算符重载

    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();
    
    }  
  • 相关阅读:
    闲来无事,编写一个数据迁移小工具
    Moq基础
    探索逻辑事务 TransactionScope
    IntelliJ IDEA安装及jsp开发环境搭建
    数据结构整理(二) 树
    数据结构整理(一) 线性结构
    梳理delegate相关概念
    02_Android应用界面编程_01_视图(View)组件
    01_Android应用开发环境_05_签名android应用程序
    01_Android应用开发环境_04_Android常用开发工具的用法
  • 原文地址:https://www.cnblogs.com/love-life-insist/p/12831617.html
Copyright © 2011-2022 走看看