Attention points for C + + operator overloading

Source: Internet
Author: User

Operator overloading includes: binocular operator overloading, monocular operator overloading, stream operator overloading, conversion constructors, type conversion functions

The functions of overloaded operators are generally formatted as follows:
function type operator operator name (formal parameter table column)
Overloaded handling of operators

1. Binocular operator Overloading

Binocular: Operators with 2 operands
An overloaded function can be a class member function or a friend function of a class:
-When it is a member function, there is a hidden parameter (the current class), so there is only one display parameter:
Complex operator+(const Complex &b);
Complex operator+(const double &d);
-When a friend function, you must explicitly give two parameters, the reason is to use the friend function, is to overload the operator as global :

Complex c(1,1);Complex10.0; // 正确Complex10.0 + c; // 错误

For line 3rd, you cannot get the operation from the floating-point number "10.0".
Therefore, if you declare an overloaded function as a friend function, you can globally match the parameters of 10.0 and C.

#include <iostream>using namespace STD;classComplex {Private:DoubleRealDoubleImag Public: Complex (DoubleRealDoubleIMAG) { This->real = Real; This->imag = Imag;} Complex () {real =0.0; imag =0.0;}//Conversion constructor: only one parameter Public: Complexoperator+(ConstComplex &b);friendComplexoperator+(ConstComplex &c,Const Double& D);friendComplexoperator+(Const Double& D,ConstComplex &c);//friend function can    voidPrint () {if(Imag <0)cout<< Real << imag <<"I"<< Endl;Else             cout<< Real <<"+"<< Imag <<"I"<< Endl; }};//member function overloadingComplex Complex::operator+(ConstComplex &b) {returnComplex ( This->real+b.real, This-&GT;IMAG+B.IMAG);}the//friend function cannot omit parameters, overloading into a global operatorthe//friend function can access private members of the friend classComplexoperator+(Const Double&d,ConstComplex &c) {returnComplex (C.real+d, c.imag);} Complexoperator+(ConstComplex &c,Const Double&AMP;D) {returnComplex (C.real+d, c.imag);}intMain () {Complex A (1,-2); Complex B (3,-1);    Complex C = a+b; Complex f =Ten+a; Complex g = B +Ten;    C.print ();    F.print (); G.print ();}
2. Single-Mesh operator overloading

The focus of the discussion is on the increment self-decrement operator overload. Refer to the following procedure to observe:
The difference between a prefix operator and a postfix operator overload is that it has a parameter int, and the return value is different:
C + + provisions: prefix operator, returns the increment or decrement of the object's reference; Postfix operator, returns the copy of the increment or decrement object before it is incremented or reduced

operator// 前缀式,++i;operator++(int// 后缀式,i++

A time-based class routine is as follows:

#include <iostream>using namespace STD;classTime {Private:intMinuteintSec Public: Time (): Minute (0), SEC (0) {}; Time (intMints): Minute (m), SEC (s) {};//prefix operator, which returns the reference to the increment or decrement object;Timeoperator++() {if(++sec >= -) {minute++; Sec-= -; }return* This; }//suffix operator, which returns a copy of the increment or decrement object before it is incremented or reducedTimeoperator++(int) {Time Temp (* This); ++(* This);returnTemp//The object itself has implemented a self-increment operation, but returned a copy that was not self-increment}voidPrint () {cout<< minute <<":"<< sec << Endl; }};intMain () {cout<<"Start time 12:58"<< Endl; Time Time1 ( A, -); for(inti =0; I <5;    i++) {(++time1). print (); }cout<<"Start time 22:58"<< Endl; Time Time2 ( A, -); for(inti =0; I <5;    i++) {(time2++). print (); }}
3. Stream operator Overloading

The functions for the "<<" and ">>" overloads are as follows:
IStream & operator >> (IStream &, custom classes &);
Ostream & operator << (ostream &, custom classes &);
The first parameter of the function that overloads the operator ">>" and the type of the function must be the istream& type, and the second argument is the class to enter the operation. The first argument and function of a function that overloads "<<" must be of type ostream&, and the second argument is the class to which the output operation is performed. Therefore, you can only overload functions that are overloaded with ">>" and "<<" as friend functions or normal functions, and you cannot define them as member functions.
Operator overloading has a return value in order to return the status of input/output for continuous input and output.
See more:
The code case references the code block in the binocular operator.

#include <iostream>using namespace STD;classComplex {Private:DoubleRealDoubleImag Public: Complex (DoubleRealDoubleIMAG) { This->real = Real; This->imag = Imag;} Complex () {real =0.0; imag =0.0;} Public:friendistream&operator>> (IStream &, Complex &);friendostream&operator<< (Ostream &, Complex &);};//stream operator overloadingistream&operator>> (IStream &input, Complex &c) {input >> c.real >> c.imag;returnInput//Return stream input object for continuous input}ostream&operator<< (ostream &output, Complex &c) {output << c.real;if(C.imag >=0) Output <<"+"; Output << C.imag <<"I"<< Endl;returnOutput;}intMain () {Complex x, y;Cin>> x >> y;cout<< x << y;}
4. Conversion constructors

The transform constructor has only one formal parameter, such as
Complex(double r) {real=r;imag=0;}
The function is to convert the parameter r of the double type to the object of the complex class, the R as the real part of the complex number, and the imaginary part to 0.
and operator overloading mates to simplify the implementation of operator overloading.
As shown below, only one operator + overload and conversion constructor is required to satisfy all + operations and to satisfy the commutative law. Note that the above operator overloads must be in the form of a friend function or a normal function (non-member function).

#include <iostream>using namespace std;classComplex {Private:Double Real;DoubleImag Public: Complex (Double Real,DoubleIMAG) { This-Real=Real; This->imag = Imag;} Complex () {Real=0.0; imag =0.0;}//Conversion constructor: only one parameterComplex (Double Real) { This-Real=Real; This->imag =0; } Public: Friend Complex operator+ (ConstComplex &a,ConstComplex &b);voidPrint () {if(Imag <0) cout <<Real<< Imag <<"I"<< Endl;Elsecout <<Real<<"+"<< Imag <<"I"<< Endl; }}; Complex operator+ (ConstComplex &a,ConstComplex &b) {returnComplex (A.Real+b.Real, A.imag+b.imag);}intMain () {Complex A (1,-2); Complex B (3,-1);    Complex E = a + b;    E.print (); Complex f =Ten+ A;//automatically converts 10 to an instance of complexF.print (); Complex g = A +Ten; G.print ();}
5. Type conversion

The transformation constructor allows you to convert data of a specified type into an object of a class. However, you cannot turn an object of a class into another type of data, such as converting a complex class object to a double type of data.

C + + provides type conversion functions (the type conversion function) to solve this problem. the function of a type conversion function is to convert an object of one class into another type of data. If you have declared a complex class, you can define a type conversion function in the complex class like this:
Operator double ()
return real;
Note: there is no function return type, no parameters. The return type is automatically consistent with the type name of the overload. Type Conversion functions can only be used as member functions (objects of this class are converted).

#include <iostream>using namespace STD;classComplex {Private:DoubleRealDoubleImag Public: Complex (DoubleRealDoubleIMAG) { This->real = Real; This->imag = Imag;} Complex () {real =0.0; imag =0.0;}operator Double() {returnReal } Public:voidPrint () {if(Imag <0)cout<< Real << imag <<"I"<< Endl;Else             cout<< Real <<"+"<< Imag <<"I"<< Endl; }};intMain () {Complex A (1,-2); Complex B (3,-1);DoubleD = A +Ten;cout<< d << Endl;cout<< A +Ten<< Endl;cout<<Ten+ b << Endl;}

Reference: C + + operator overloading details-what are operator overloading, operator overloading methods, and rules

Attention points for C + + operator overloading

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.