연산자 중복
여러가지 연산자들을 클래스 객체에 대해서도 적용하는 것
- 연산자를 함수로 구현
❗ 주의할 점
- 새로운 연산자 만드는 것 허용 X
- ::, *, ., ?: 연산자 중복 불가능
- 내장된 int형이나 double형에 대한 연산자의 의미 변경 불가능
- 연산자들의 우선 순위나 결합 법칙은 변경 X
- +, - 연산자를 오버로딩하였으면 일관성을 위해 +=, -= 연산자도 오버로딩하는 것이 좋음
- 산술 연산자와 관계 연산자는 비멤버 함수로 정의 (참여하되 안바뀌는 것)
- 할당 연산자는 멤버 함수로 정의 (참여해서 바뀌는 것)
프렌드 함수
클래스의 내부 데이터에 접근할 수 있는 특수한 함수
- 선언 방법
- 프렌드 함수의 원형은 비록 클래스 안에 포함되지만 멤버 함수는 아님
- 프렌드 함수의 본체는 외부에서 따로 정의
- 프렌드 함수는 클래스 내부의 모든 멤버 변수를 사용 가능
- 프렌드 클래스도 가능
- 교환 법칙 성립 X
연산자 중복 구현 방법
비멤버 함수(friend)
- 참여는 하지만 결과가 변하지 않으면 비멤버 (ex. +연산)
- v1 + v2 ⇒ operator+ (v1, v2)
// 복소수 예제
friend Complex operator+(const Complex& c, const Complex& d);
Complex operator+(const Complex& c, const Complex& d){
Complex result(c.re + d.re, c.im + d.im);
return result;
}
- cout << v1 << ⇒ operator<< (cout, v1)
- 연산을 수행한 후 다시 스트림 객체 반환
- 레퍼런스이기 때문에 체인 연산 가능
using namespace std;
friend ostream& operator<<(ostream& os, const Complex& c);
friend ostream& operator<<(ostream& os, const Complex& c){ return os; }
멤버 함수
- 결과가 변하면 멤버 (ex. +=연산)
- v1 + v2 ⇒ v1.operator+(v2)
Complex operator+(const Complex& c);
Complex Complex::operator+(const Complex& c){
Complex result(re + c.re, im + c.im);
return result;
}
- = 연산
- 구현하지 않으면 컴파일러가 자동 생성
- 반드시 호출한 객체의 레퍼런스 반환
- 깊은 복사가 필요한 경우 구현
Complex& operator=(const Complex& c);
Complex& Complex::operator=(const Complex& c){
re = c.re; im = c.im;
return *this;
}
- prefix++, postfix++ 연산
Complex& operator++() {
re++;
return *this;
}
Complex operator++(int) {
Complex t(*this);
operator++();
return t;
}
타입 변환
- 클래스의 객체들도 하나의 타입에서 다른 타입으로 자동적인 변환 가능
- 변환 생성자, 변환 연산자
class Book{
private:
int isbn;
string title;
public:
Book(int isbn, string& title){
this->isbn = isbn;
this.title = title;
}
// 변환 생성자
Book(int isbn){
this->isbn = isbn;
this.title = "unknown";
}
// 변환 연산자
operator int() const{
return isbn;
}
bool check(int isbn){
return true;
}
int main(){
Book b1 = 12345; // int -> Book 변환 생성자
int isbn = b1; // Book -> int 변환 연산자
check(b1); // Book -> int 변환 연산자
}
- 변환 생성자/연산자 앞에 explicit 선언을 하면 컴파일러가 자동적으로 타입 변환을 하지 못함
class Complex{
double re, im;
public:
Complex(double r=0, double i=0): re(r), im(i){}
operator double() const { return re; }
~Complex(){}
int main(){
Complex x(2, 3);
Complex y(-1, -3), z;
double d = 2.71828;
z = 3.14; // double -> Complex (implicit)
d = y; // Complex -> double (implicit)
z = Complex(d) // double -> Complex (explicit)
d = double(x); // Complex -> double (explicit)
728x90
반응형
'C++' 카테고리의 다른 글
[C++] Polymorphism (0) | 2024.04.30 |
---|---|
[C++] Inheritance (0) | 2024.04.30 |
[C++] Namespace (0) | 2024.04.30 |
[C++] Objects (0) | 2024.04.30 |
[C++] Constructors and Destructors (0) | 2024.04.30 |