(리턴 타입) operator(연산자) (연산자가 받는 인자)
ex) bool operator==(MyString& str);
ex) 복소수 클래스 생성
#include<iostream>
using namespace std;
class Complex
{
private:
double real, img;
public:
Complex(double real, double img) : real(real), img(img) {}
Complex(const Complex& com) { real = com.real; img = com.img; }
Complex operator+(const Complex& com) const;
Complex operator-(const Complex& com) const;
Complex& operator=(const Complex& com);
void println() { printf("%f+%fi\n", real, img); }
};
Complex Complex::operator+(const Complex& com) const
{
Complex temp(real + com.real, img + com.img);
return temp;
}
Complex Complex::operator-(const Complex& com) const
{
Complex temp(real - com.real, img - com.img);
return temp;
}
Complex& Complex::operator=(const Complex& com)
{
real = com.real;
img = com.img;
return *this;
}
int main()
{
Complex a1(1, 2);
Complex a2(2, 3);
Complex a3 = a1 + a2;
a3.println();
return 0;
}
주의 할 점은 사칙연산 operater 는 꼭 return 값을 class 를 새로 생성해서 줘야하고 ,
대입연산자는 자기자신을 수정해야 한다.
출처:
씹어먹는 C++ - <5 - 2. 입출력, 첨자, 타입변환, 증감 연산자 오버로딩>
modoocode.com
씹어먹는 C++ - <5 - 1. 내가 만든 연산자 - 연산자 오버로딩>
modoocode.com
'공부,일 > C++' 카테고리의 다른 글
erase (0) | 2021.11.06 |
---|---|
map (0) | 2021.10.24 |
복사 생성자 (0) | 2021.10.18 |
Temporary Object (0) | 2021.10.17 |
string 클래스 (0) | 2021.08.25 |
댓글