Computer Language/C++
[C++] Operator Overloading 1
정우섭
2020. 5. 2. 18:47
Operator overloading literally means overloading the operators.
You might have a curiosity about the meaning of operator overloaing.
But first, let's see the following code.
Global
#include <iostream>
using namespace std;
class Point {
private:
int x, y;
public:
Point(int _x=0, int _y=0):x(_x), y(_y){}
void ShowPosition();
friend Point operator+(const Point& ref1, const Point& ref2);
/**************************************************************
friend declare to global function
(keyword friend is usually used in operator overloading)
operator+ function can access the private member of Point class
**************************************************************/
};
void Point::ShowPosition(){
cout<<x<<" "<<y<<endl;
}
Point operator+(const Point& ref1, const Point& ref2) //global function
{
Point temp(ref1.x+ref2.x, ref1.y+ref2.y);
return temp;
}
int main(void)
{
Point p1(1, 2);
Point p2(2, 1);
Point p3 = p1+p2;
p3.ShowPosition();
Point p4 = operator+(p1, p2);
p4.ShowPosition();
return 0;
}
Result
3 3
3 3
Local
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
#include <iostream>
using namespace std;
class Point {
private:
int x, y;
public:
Point(int _x=0, int _y=0):x(_x), y(_y){}
void ShowPosition() const
{
cout<<x<<" "<<y<<endl;
}
Point operator+(const Point& ref) //local function
{
Point temp(x+ref.x, y+ref.y);
return temp;
}
};
int main(void)
{
Point p1(1, 2);
Point p2(2, 1);
Point p3 = p1+p2;
p3.ShowPosition();
p4 = p1.operator+(p2);
p4.ShowPosition();
return 0;
}
|
Result
|
3 3
3 3
|
These are the ways of operator overloading with global function and local function.
Point p3 = p1+p2;
Basically the compiler cannot complie this code.
But by using operator overloading it is available, because p1+p2 is translated into p1.operator+(p2) or operator+(p1, p2) by the compiler.
Warning
- Operator overloading should be coded following the function of the operator.
- The function of the operator can overloaded, but the operator precedence and associativity don't change.
- Impossible to set default value of the parameter.
- The pure function of the operator cannot be changed.
Impossible to Overload
. (member access operator)
.* (pointer-to-member operator)
:: (scope resolution operator)
?: (ternary operator)
sizeof
typeid
static_cast
dynamic_cast
const_cast
reinterpret_cast
[참고자료]
- 윤성우의 열혈 C++ 프로그래밍