Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the operator keyword in C++

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

I believe many inexperienced people don't know what to do about how to use the operator keyword in C++. Therefore, this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

First, why use operator overloading?

For all operators of the system, in general, only basic data types and class provided in the standard library are supported. For user-defined class, if you want to support basic operations, such as comparing size, judging equality, etc., you need to define the specific implementation of this operator. For example, to judge whether two people are the same age, our default rule is to compare according to their age, so when designing the person class, we need to consider the operator = =, and, according to the analysis just now, the comparison should be based on age. So why is it called overloading? This is because, at the time of the compiler implementation, we have been provided with an implementation version of the basic data type of this operator, but now his Operand has become a user-defined data type class, so it is necessary for the user to provide the implementation of this parameter version.

Second, how to declare an overloaded operator?

A: operator overloading is implemented as a class member function

The overloaded operator is declared in the class body in the same way as a normal member function, except that its name contains the keyword operator, followed by a C++ predefined operator.

You can declare a predefined = = operator as follows:

Class person {

Private:

Int age

Public:

Person (int a) {

This- > age=a

}

Inline bool operator = (const person & ps) const

}

The implementation is as follows:

Inline bool person::operator== (const person & ps) const

{

If (this- > age==ps.age)

Return true

Return false

}

The calling method is as follows:

# include

Using namespace std

Int main ()

{

Person p1 (10)

Person p2 (20)

If (p1==p2) cout

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report