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

Unary and binary operator overloading in C++

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article is mainly about "unary and binary operator overloading in C++". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "unary and binary operator overloading in C++".

Operator overloading is to redefine an existing operator and give it another function to adapt it to different data types.

The essence of operator overloading: function overloading keyword: operator

Unary operator overloading

The unary operator is to operate on a number

When unary operator overloading uses member functions for overloading, there is no need to pass parameters to (). There is a hidden * this in ()

Overloading of minus operator

Define a Coordinate coordinate class that overloads the minus operator through member functions and friend functions, respectively.

Overload the minus operator through member functions:

# include

Using namespace std

/ * *

Unary operator overloading

Request:

Define a Coordinate coordinate class

Member functions: construction, getX, getY, data member: mSecretiX _ mcm _ iY

1. Negative operator overloading (member function, friend function)

2. + operator overloading (pre-+, post-+)

* * /

Class Coordinate

{

Coordinate (int x pencil int y)

/ / overload symbolic operators through member functions

Coordinate & operator- (); / / it is itself that asks him to return, so that he can operate on the minus operator again, so the return value is written as Coordinate &

Int getX ()

Int getY ()

Private:

Int m_iX

Int m_iY

}

Coordinate::Coordinate (int x pencil int y)

{

M_iX = x

M_iY = y

}

Int Coordinate::getX ()

{

Return m_iX

}

Int Coordinate::getY ()

{

Return m_iY

}

/ / member function to realize negative sign operator overloading

Coordinate & Coordinate::operator- ()

{

This- > m_iX =-(this- > m_iX); / / m_iX =-m_iX

This- > m_iY =-(this- > m_iY)

Return * this;// returns an object

}

Int main ()

{

Coordinate coor1 (1pr 3)

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