Operator overloading in C ++: basics, examples

, . , , , . (x + y * z) , « y, , z x». , XVI , , . . . , . .

, C++ , , . . , C++. , . , , . , sum_matrix (A, B) , A + B.

Complex number representation




:





//         .
class complex {
	double re, im; 
public:
	complex (double r, double i) :re(r), im(i) {} //
	complex operator+(complex);	// 
	complex operator*(complex); // 
};

void main() {
	complex a{ 1, 2 }, b{ 3, 4 }, c{0, 0};
	c = a + b;
	c = a.operator+(b); ////       ,    a+b
	c = a*b + complex(1, 3); //       
}
      
      



, , / C++ .

,

, :

+

-

*

/

%

^

&

|

~

!

=

<

>

+=

-=

*=

/=

%=

^=

&=

|=

<<

>>

>>=

<<=

==

!=

<=

>=

&&

||

++

--

->*

,

->

[]

()

new

new[]

delete

delete[]

, . . . Java, , . .

,

  • – «::»;
  • – «.»;
  • – «.*»;
  • – «?:»;
  • sizeof;
  • typeid.

, . . , - , Python.









:

Chart of operators available for overload




  • , .
  • , . . , , .
  • , . new delete. , , . , , . "=", "&" "," .
  • , C++, .
  • operator, .
  • , . , : ++x; x + = 1; x = x + 1. . .
  • . z + 5 5 +z ( z – ) -. «complex + », - « + ». .
  • - , , . .

.

Binary operation




- . @ a@b, @ :

a.operator@(b) operator@(a, b).

.

class complex {
	double re, im;
public:
	complex& operator+=(complex z);	
	complex& operator*=(complex z); 
};
// 
complex operator+(complex z1, complex z2);
complex operator+(complex z, double a);

      
      



, , , . .

, – , -, . : (, a + = b), , ; (, a + b) – .

Unary and binary operations




C++ , , :

  • , , – @a, , ++i. o a.operator@() operator@(aa);
  • , , – b@, , i++. o b.operator@(int) operator@(b, int)

, , , , C++.

Types of C ++ Operators




@ x X y Y. x@y :

  1. X , operator@ X, X;
  2. , x@y;
  3. X N, N;
  4. Y M, M.

1-4 operator@, .

.

complex

, .

class complex {
	double re, im;
public:
	complex& operator+=(complex z) { //    z1 += z2
		re += z.re;
		im += z.im;
		return *this;
	}
	complex& operator+=(double a) { //    z1 += 5;
		re += a;
		return *this;
	}
	complex (): re(0), im(0) {} //    .  ,         (0, 0)
	complex (double r): re(r), im(0) {} //      complex z = 11;   z = complex(11);
	complex (double r, double i): re(r), im(i) {} //
};
complex operator+(complex z1, complex z2) { //    z1 + z2
	complex res = z1;
	return res += z2; // ,   -
}
complex operator+(complex z, double a) { //   z+2
	complex res = z;
	return res += a;
}
complex operator+(double a, complex z) { //   7+z
	complex res = z;
	return res += a;
}
//…

      
      



, , . . , C++ .

. , , . 3 , 9 – 27 – . .

«[]» , . , , , .

«()» . , «( )» () «», – . operator()() .

«,» () , . .

«->» . . , , .

- .

«=», «&» «,» public.

. , – . , - .

What is polymorphism




. , . . , .

Creator of C ++ Bjarne Stroustrup




  1. . . , .
  2. .
  3. .
  4. , .
  5. , .
  6. - - , .
  7. .
  8. - .
  9. () .
  10. .




All Articles