연산자 operator, function overloading은 매우 중요하다.
특히 operator는 stl과 결합하여 아주 강력한 코딩을 만들 수 있다.
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
#include <iostream>
#include <string>
#include <vector>
class Cat
{
public:
Cat(std::string name, int age) : mName{ std::move(name) }, mAge{ age } {};
const std::string& name() const
{
return mName;
};
int age() const
{
return mAge;
};
void print(std::ostream& os) const
{
os << mName << " " << mAge << std::endl;
};
private:
std::string mName;
int mAge;
};
bool operator==(const Cat& lhs, const Cat& rhs)
{
return lhs.age() == rhs.age() && lhs.name() == rhs.name();
}
bool operator<(const Cat& lhs, const Cat& rhs)
{
if (lhs.age() < rhs.age())
{
return true;
}
else
return false;
return lhs.age() == rhs.age() && lhs.name() == rhs.name();
}
std::ostream& operator<<(std::ostream& os, const Cat& c)
{
return os << c.name() << c.age();
}
struct complexNum
{
double real;
double imag;
complexNum(double r, double i) : real{ r }, imag{ i } {};
void print() const
{
std::cout << real << " " << imag << "i" << std::endl;
}
};
complexNum operator+(const complexNum& lhs, const complexNum& rhs)
{
complexNum c{ lhs.real + rhs.real, lhs.imag + rhs.imag };
return c;
}
int main()
{
complexNum c1{ 1,1 };
complexNum c2{ 1,2 };
complexNum c{ c1 + c2 };
c.print();
Cat kitty{ "kitty", 1 };
Cat nabi{ "nabi", 2 };
if (kitty == nabi)
{
std::cout << "They are same" << std::endl;
}
else
{
std::cout << "They are different!" << std::endl;
}
if (kitty < nabi) std::cout << "nabi is older" << std::endl;
else std::cout << "kitty is older" << std::endl;
kitty.print(std::cout);
nabi.print(std::cout);
// std::ostream& operator로 구현
std::cout << kitty << std::endl;
std::cout << nabi << std::endl;
return 0;
}
|
'C' 카테고리의 다른 글
c++ heap 메모리 생성, 해제, unique_ptr, shared_ptr (0) | 2021.06.23 |
---|---|
c++ const, explicit (0) | 2021.06.23 |
C++ class copy move constructor, instructor (0) | 2021.06.23 |
static function, static variable (0) | 2021.06.23 |
c++ object memory alignment (0) | 2021.06.23 |