반응형
안녕하세요. 훈츠입니다. 금일은 연산자 오버로딩에 관해 포스팅 합니다.
연산자 오버로딩
연산자 오버로딩은, 간략한 표기와 고유의 의미를 유지하여 가독성과 코드 작성을 짧게 할 수 있습니다.
- 기본 연산자의 기능을 객체에도 적용
- 연산자를 중복해서 정의 하는것
- 고유 연산자 기능 외에 사용자가 정의한 기능을 연산자로 실행하게 하는 것
형식
- 리턴형 Operator 연산자 (매개 변수들…)
오버로딩이 불가능한 연산자
- . (멤버 선택시 사용하는 dot) , .* , ?:, sieof
- :: (범위 한정 연산자)
오버로딩 예시
- 이항 연산자인 사칙 연산자
- 단항 연산자인 증가 연산자 ++ (전치형, 후치형)
코드1
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
|
//Hoons Blog---https://rain2002kr.tistory.com------------------------------------------------------------------코드///
class A
{
private: int mVar;
public:
int operator +(A& refA) {
}
int operator -(A& refA) {
}
int operator *(A& refA) {
}
int operator /(A& refA) {
}
int Get() {
return mVar;
}
A(int nVar) : mVar(nVar) {}
};
int main()
{
A t1(20), t2(10);
cout << "+ 연산자 오버로딩 " << t1 + t2 << endl;
cout << "- 연산자 오버로딩 " << t1 - t2 << endl;
cout << "* 연산자 오버로딩 " << t1 * t2 << endl;
cout << "/ 연산자 오버로딩 " << t1 / t2 << endl;
return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs |
코드2
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
|
//Hoons Blog---https://rain2002kr.tistory.com------------------------------------------------------------------코드///
class B
{
private: int mVar;
public:
void operator ++() {
++mVar;
cout << "전치 ++ 호출 : "<< mVar << endl;
}
void operator ++(int i) {
mVar++;
cout << "후치 ++ 호출: " << mVar << endl;
}
void Print() { cout << mVar << endl; }
B(int nVar) : mVar(nVar) {};
};
int main()
{
B test(1);
++test;
test++;
return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs |
'컴퓨터 언어 > C++' 카테고리의 다른 글
[C++] C++ 17일차 오버로딩 3 (클래스 객체 복사시 주의사항) (0) | 2020.04.21 |
---|---|
[C++] C++ 16일차 함수 오버로딩 2 (0) | 2020.04.20 |
[C++] C++ 14일차 가상함수와 추상클래스 (0) | 2020.04.16 |
[C++] C++ 13일차 가상함수와 다형성 (0) | 2020.04.15 |
[C++] C++ 12일차 상속 4 (0) | 2020.04.14 |