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.

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 1Load 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