Gone are learning C ++ Advanced Series: overloaded functions and overloaded operators

C ++ allows a certain scope of the same functions and operators specify DeclDefs, called function overloading and operator overloading .

Before a claim is overloaded already declared in the scope of the method has the function declaration or the same name, but the list of parameters and their definitions (realized) are not the same. Overload resolution refers to invoked a overloaded function or operator overloading , the compiler by Parameter Type declaration defines the type used in the comparison, it determines the most appropriate choice of process definition statement.

Function overloading

The same scope, but functionally similar forms allows the declaration of parameters (parameter refers to the number, type or sequentially) with the same name have different functions, but not overloaded function return types. Namesake functions such as  print () to output different types of data:

class printData
{
   public:
      void print(int i) {
        cout << "整数为: " << i << endl;
      }
 
      void print(double  f) {
        cout << "浮点数为: " << f << endl;
      }
 
      void print(char c[]) {
        cout << "字符串为: " << c << endl;
      }
};

Function of the same name  print ()  based on the parameters passed to determine which type of function using an overloaded.

Operator overloading

C ++ allows redefinition or override most built-in operators. Operator is overloaded with special function name , the function name and the keyword operator and subsequent to override operator symbols configuration.

Overloaded operators have a return type and an argument list:

returnType operator+(params lists);

Most overloaded operator may be defined as a normal or non-member function is defined as a class member function. For operator overloads when a non-member of a class of functions, it is necessary to have the object to be operated as a parameter declaration.

Overload operators can / can not be overloaded operators

May be overloaded operators

Arithmetic operators binocular + (Plus), - (minus), * (multiplication), / (division),% (modulo)
Relational Operators == (equal to),! = (Not equal to), <(less than),> (greater than>, <= (less than or equal),> = (greater than or equal)
Logical Operators || (logical OR), && (logical AND),! (Logical NOT)
Unary operator + (Positive), - (minus), * (pointer), & (address)
Increment decrement operator ++ (increment), - (decrement)
Bitwise Operators | (Bitwise or) & (bitwise and) ~ (bitwise) ^ (bitwise exclusive or) ,, << (shift left), >> (shift right)
Assignment Operators =, +=, -=, *=, /= , % = , &=, |=, ^=, <<=, >>=
Space application and release new, delete, new[ ] , delete[]
Other Operators () (Function call), -> (member access),, (comma), [] (subscript)

 Not overloaded operators

Member access operator  .
Access operator member pointer  .* ->*
Operator domain  :: 
Operators length  sizeof
Conditional operator  ? :
Preprocessor symbol  #

Examples of operator overloading

Binary operator overload

In Case + operator (the sum of the two objects Box):

// 重载 + 运算符,用于把两个 Box 对象相加
Box operator+(const Box& b)
{
    Box box;
    box.length = this->length + b.length;
    box.breadth = this->breadth + b.breadth;
    box.height = this->height + b.height;
    return box;
}

Overloading Unary

The increment and decrement operator overloading

  1. Increment and decrement the general state of the object is changed, it is generally overloaded as a member function.
  2. Overloaded gradual increase and decrease, and be sure to increment the pointer is decremented distinguished. Because here overloaded operator is an object, not a pointer (because the pointers are built-in types, pointer increment decrement is not overloaded), it is generally decreasing increments member variables within the operating object.

To increment operator ++ example:

// 重载前缀递增运算符( ++ )
Time operator++ ()  
{
    ++minutes;          // 对象加 1
    if(minutes >= 60)  
    {
        ++hours;
        minutes -= 60;
    }
    return Time(hours, minutes);
}
// 重载后缀递增运算符( ++ )
Time operator++( int )         
{
    // 保存原始值
    Time T(hours, minutes);
    // 对象加 1
    minutes++;                    
    if(minutes >= 60)
    {
        hours++;
        minutes -= 60;
    }
    // 返回旧的原始值
    return T; 
}

Prefix operator first increment, the calculation expression, the opposite postfix operators. Prefix form overloaded call operator ++ (), postfix reload the form of call operator ++ (int). int to illustrate the compiler which is in the form of a suffix, rather than an integer in parentheses.

Relations Operator Overloading

To <example:

// 重载小于运算符( < )
bool operator <(const Distance& d)
{
     if(feet < d.feet)return true;
     if(feet == d.feet && inches < d.inches)return true;
     return false;
}

Input / output operators << and >> reload

Operators can be overloaded and extracting stream insertion operator to manipulate objects and other user-defined data types. Here, the need to operator overloading function declared as class friend function , so we can not create an object and calling the function directly . A flow insertion operator << Example:

//重载插入运算符 <<
friend ostream &operator<<( ostream &output, const Distance &D )
{ 
    output << "F : " << D.feet << " I : " << D.inches;
    return output;            
}
//重载提取运算符 >>
friend istream &operator>>( istream  &input, Distance &D )
{ 
    input >> D.feet >> D.inches;
    return input;            
}

Assignment Operator Overloading

Overload assignment operator (=), is used to create an object, such as a copy constructor.

// 所需的构造函数
Distance(){
   feet = 0;
   inches = 0;
}
Distance(int f, int i){
    feet = f;
    inches = i;
}
//重载赋值运算符 =
void operator=(const Distance &D )
{ 
    feet = D.feet;
    inches = D.inches;
}

When a user-defined type variable to the built-in type variable time assignment, may be used to customize the type of implicit conversion:

#include<iostream>
using namespace std;

class Int{
  private:
    int n;
  public:
    Int(int i){
        n = i;
    {
    operator int() // 这里就是隐式转换声明,应注意到它与运算符重载的不同之处
    {
       return n;
    }
};

int main()
{
  Int a(5);
  int c=a; // 隐式调用转换函数
  cout<<c<<endl;
  cout<<a<<endl; // 由于未重载Int的<<操作符,将隐式调用转换函数
}

The output of the code will be:

5
5

Function call operator () Overloaded

Function call operator () can be overloaded for an object class. When the heavy load (), you are not creating a new way of calling a function, on the contrary, it is to create a number of arguments that can be passed to any operator functions:

// 重载函数调用运算符
Distance operator()(int a, int b, int c)
{
    Distance D;
    // 进行随机计算
    D.feet = a + c + 10;
    D.inches = b + c + 100 ;
    return D;
}
// 调用 operator()
D2 = D1(10, 10, 10); 

Subscript operator [] overloaded

Subscript operator [] is generally used to access array elements. Overload operator is used to enhance the functional operation of the array C ++:

//下标运算运算符[] 重载
int& operator[](int i)
{
    if( i > SIZE ){
        cout << "索引超过最大值" <<endl; 
        // 返回第一个元素
        return arr[0];
    }
    return arr[i];
}

Class member access operator -> reload

Class member access operator (->) can be overloaded, but it is cumbersome. It is defined as given for the "pointer" act as a class. Class member access operator -> must be a member function. If the -> operator, return type must be a class or object pointer . Class member access operator -> generally with reference pointer operator * in combination, for achieving "smart pointers" function. These pointers are similar to the normal behavior of the object pointer, the only difference is, when the object is accessed through a pointer, they will perform other tasks. For example, when the pointer is destroyed, or when a pointer to another object, the object will be automatically deleted.

Indirection operator -> can be defined as a unary postfix operators. In other words, given a class Ptr, Ptr class of objects that can be used to access a member of class X, use the pointer usage is very similar. For example: d

class Ptr{
   // -> 运算符重载
   X * operator->();
};

void f(Ptr p )
{
   p->m = 10 ;
}

 For example, heavy-duty class member access operator ->:

#include <iostream>
#include <vector>
using namespace std;
 
// 假设一个实际的类
class Obj {
   static int i, j;
public:
   void f() const { cout << i++ << endl; }
   void g() const { cout << j++ << endl; }
};
 
// 静态成员定义
int Obj::i = 10;
int Obj::j = 12;
 
// 为上面的类实现一个容器
class ObjContainer {
   vector<Obj*> a;
public:
   void add(Obj* obj)
   { 
      a.push_back(obj);  // 调用向量的标准方法
   }
   friend class SmartPointer;
};
 
// 实现智能指针,用于访问类 Obj 的成员
class SmartPointer {
   ObjContainer oc;
   int index;
public:
   SmartPointer(ObjContainer& objc)
   { 
       oc = objc;
       index = 0;
   }
   // 返回值表示列表结束
   bool operator++() // 前缀版本
   { 
     if(index >= oc.a.size() - 1) return false;
     if(oc.a[++index] == 0) return false;
     return true;
   }
   bool operator++(int) // 后缀版本
   { 
      return operator++();
   }
   // 重载运算符 ->
   Obj* operator->() const 
   {
     if(!oc.a[index])
     {
        cout << "Zero value";
        return (Obj*)0;
     }
     return oc.a[index];
   }
};
 
int main() {
   const int sz = 10;
   Obj o[sz];
   ObjContainer oc;
   for(int i = 0; i < sz; i++)
   {
       oc.add(&o[i]);
   }
   SmartPointer sp(oc); // 创建一个迭代器
   do {
      sp->f(); // 智能指针调用
      sp->g();
   } while(sp++);
   return 0;
}

 

Published 161 original articles · won praise 90 · views 50000 +

Guess you like

Origin blog.csdn.net/qq_42415326/article/details/104032587