Table of Contents
Overload the One-seat Operator in C ++ is easier to understand when the core ideas are paired with practical examples. The sections below explain the topic clearly, highlight useful steps, and point out details that can prevent common errors.
The unary operator in C ++ operates on a single operand and here are some examples of single-operator operators:
Overloading the increment operator (++) and decreasing operator (-) in C ++.
Operator unary (-) in C ++
Negative logical operator (!) In C ++
The unary operator operates on the object to which they are called, and typically this operator appears to the left of the object, such as :! Obj, -obj, and ++ obj , but sometimes they can be used as is suffix like obj ++ or obj-- .
the example below explains how the (-) operator can be overloaded with the use of the prefix as well as the suffix.
#include using namespace std ; class KhoangCach { private : int met ; int centimet ; public : // khai bao cac constructor KhoangCach (){ met = 0 ; centimet = 0 ; } KhoangCach ( int m , int c ){ met = m ; centimet = c ; } // phuong thuc de hien thi khoang cach void hienthiKC () { cout << "Khoang cach bang m la: " << met << endl ; cout << "Khoang cach bang cm la: " << centimet << endl ; cout << "nn================================nn" << endl ; } // nap chong toan tu (-) KhoangCach operator - () { met = - met ; centimet = - centimet ; return KhoangCach ( met , centimet ); } }; int main () { KhoangCach K1 ( 20 , 6 ), K2 (- 6 , 15 ); - K1 ; // ap dung su phu dinh K1 . hienthiKC (); // hien thi K1 - K2 ; // ap dung su phu dinh K2 . hienthiKC (); // hien thi K2 return 0 ; }
Compiling and running the above C ++ program will produce the following results:
Hopefully the above example will help you understand this concept and you can apply for operator operator (!) In C ++.
According to Tutorialspoint
Previous post: Load operator and Load overlap in C ++
Next lesson: Overload binary operator in C ++
Frequently Asked Questions
What is Overload the One-seat Operator in C ++?
The unary operator in C ++ operates on a single operand and here are some examples of single-operator operators: Overloading the increment operator (++) and decreasing operator (-) in C ++.
Why is Overload the One-seat Operator in C ++ important?
A clear understanding of Overload the One-seat Operator in C ++ helps you make informed decisions, avoid common mistakes, and use the relevant tools or techniques more effectively.
How should beginners approach Overload the One-seat Operator in C ++?
Start with the fundamental concepts, follow the examples step by step, and test each change in a safe environment before applying it to important systems or data.
Was this article helpful?
Your feedback helps us improve.
![Overload Subscript Operator [][] in C ++](/img/no-image.png)
Reader Comments 0
Sign in with email or Google to join the discussion.