Load the stack of assignment operators in C ++

You can overload the assignment operator (=) as you can with other operators in C ++ and it can be used to create an object like copying constructors.

The following example illustrates how to overload the assignment operator in C ++:

 #include using namespace std ; class KhoangCach { private : int met ; int centimet ; public : // phan khai bao cac constructor can thiet KhoangCach (){ met = 0 ; centimet = 0 ; } KhoangCach ( int m , int c ){ met = m ; centimet = c ; } void operator =( const KhoangCach & K ) { met = K . met ; centimet = K . centimet ; } // phuong thuc de hien thi khoang cach void hienthiKC () { cout << "nDo dai bang m la: " << met << "nVa do dai bang cm la: " << centimet << endl ; } }; int main () { KhoangCach K1 ( 23 , 16 ), K2 ( 15 , 46 ); cout << "Khoang cach dau tien: " ; K1 . hienthiKC (); cout << "n-------------------n" ; cout << "Khoang cach thu hai:" ; K2 . hienthiKC (); // su dung toan tu gan K1 = K2 ; cout << "n-------------------n" ; cout << "Khoang cach dau tien: " ; K1 . hienthiKC (); return 0 ; } 

Compiling and running the above C ++ program will produce the following results:

Load the stack of assignment operators in C ++ Picture 1

According to Tutorialspoint

Previous lesson: Load the operator ++ and - in C ++

Next lesson: Load the operator stack to call the function () in C ++

4 ★ | 1 Vote

May be interested

  • Load the operator stack to call the function () in C ++Photo of Load the operator stack to call the function () in C ++
    c ++ function call () can be overloaded for objects of class type. when you overload (), you are not creating a new way to call a function.
  • Overload subscript operator [] in C ++Photo of Overload subscript operator [] in C ++
    the subscript operator [] in c ++ is often used to access array elements. this operator can be overloaded to enhance existing functionality in arrays in c ++.
  • Overload class member access operator (->) in C ++Photo of Overload class member access operator (->) in C ++
    the class member access operator (->) can be overloaded, but it's quite complicated.
  • Data abstraction in C ++Photo of Data abstraction in C ++
    data abstraction involves only providing the necessary information to the outside and hiding their basic details, for example, to represent the information needed in the program without displaying the details. details about them.
  • Calculate closure in C ++Photo of Calculate closure in C ++
    encapsulation is a concept of object-oriented programming that binds data and functions that manipulate that data, and keeps them safe by preventing obstruction and external abuse. . closedness leads to the important oop concept data hiding.
  • Interface in C ++ (Abstract class)Photo of Interface in C ++ (Abstract class)
    an interface describes the behavior or capabilities of a class in c ++ without signing to a specific implementation of that class.