Discussion on C++ type conversion of operator overload function and basic operator overload of self increase and self decrease

  • 2020-05-19 05:28:09
  • OfStack

Type conversion (operator overload function)

You can use the transform constructor to convert 1 data of a specified type into an object of a class. However, you cannot convert an object of one class to one of the other types of data in reverse (for example, an object of class Complex to data of type double). The type conversion function (type conversion function) is provided in C++ to solve this problem. The type conversion function converts objects of one class to data of another type.

The general form of the type conversion function is:


operator  Type name ( ){
   The statement that implements the transformation 
}

Here is the simple implementation. At this point, Base serves two purposes: classes and data types. The system will automatically call the corresponding class method when needed.


#include <iostream>
using namespace std;

class Base{
  private:
    float x;
    int y;
  public:
    Base (float xx=0,int yy=0){
      x = xx;
      y = yy;
    }
    operator float (){
      return x;
    }
    operator int (){
      return y;
    }
    void display(){
      cout<<"x is :"<<x<<";y is :"<<y<<endl;
    }
};

int main()
{
  Base base(1.0,2);
  base.display();
  int y= base;
  float x= base;
  cout<<"NewX is :"<<x<<"NewY is:"<<y<<endl;
  return 0;
}

Basic operator overloading (self-increment and self-decrement)

This paper mainly summarizes the usage of preposition and postposition of self-increasing and self-decreasing. Other addition, subtraction, multiplication and division are simpler.

Simple code implementation (pure syntax)


#include <iostream>
using namespace std;

class Base{
  private:
    float x;
    int y;
  public:
    Base (float xx=0,int yy=0){
      x = xx;
      y = yy;
    }
    operator float (){
      return x;
    }
    operator int (){
      return y;
    }
    Base operator ++(){// Pre -  ++
      x++;
      y++;
      return *this;
    } 
    Base operator --(){
      x--;
      y--;
      return *this;
    }
    Base operator ++(int ){// The rear  ++
      Base temp = *this;
      ++(*this);
      return temp;
    }
    Base operator --(int ){
      Base temp = *this;
      --(*this);
      return temp;
    }
    void display(){
      cout<<"x is :"<<x<<";y is :"<<y<<endl;
    }
    
};

int main()
{
  Base base(1.0,1);
  Base tem = base++;
  base.display();
  tem.display(); 
  
  Base base2(1.0,1);
  tem = ++base2;
  base.display();
  tem.display(); 
  return 0;
}

Findings:

The difference between post and front is the presence or absence of the int parameter.

After the need to apply for a new space, the size is the size of the class. As a result, there is an additional time and space overhead associated with post-set operations.

Use front operations whenever possible: for (int i=0; i < n;++i)


Related articles: