728x90
반응형
2023.02.21 최초 작성
+, - 등의 연산자는 C++가 기본으로 제공하는 데이터 타입 객체를 연산할 수 있다.
하지만 사용자가 만든 클래스 타입의 객체를 연산하고자 하면 연산자 중복을 통해 사용자가 원하는 연산을 수행할 수 있다.
#include <iostream>
using namespace std;
class Rectangle {
private:
int width;
int height;
public:
Rectangle(int width=0, int height=0) {
this->width = width;
this->height = height;
}
Rectangle operator+(Rectangle r) {
Rectangle a;
a.width = this->width + r.width;
a.height = this->height + r.height;
return a;
}
bool operator==(Rectangle r) {
int a = this->width * this->height;
int b = r.width * r.height;
if (a == b) {
cout << a << "==" << b << endl;
return true;
}
cout << a << "!=" << b << endl;
return false;
}
friend bool operator<(Rectangle r1, Rectangle r2);
void printInfo() {
cout << this->width << ", " << this->height << endl;
}
};
bool operator<(Rectangle r1, Rectangle r2) {
int a = r1.width * r1.height;
int b = r2.width * r2.height;
if (a < b) {
cout << a << "<" << b << endl;
return true;
}
return false;
}
int main() {
Rectangle ret1(50, 20);
Rectangle ret2(10, 100);
Rectangle ret3 = ret1 + ret2;
ret3.printInfo();
if (ret1 == ret2) {
cout << "ret1과 ret2의 넓이가 같다." << endl;
}
else {
cout << "ret1과 ret2의 넓이가 다르다." << endl;
}
if (ret1 < ret2) {
cout << "ret1가 ret2보다 넓이가 작다." << endl;
}
else {
cout << "ret1가 ret보다 넓이가 작지 않다." << endl;
}
return EXIT_SUCCESS;
}
[실행 결과]
60, 120
1000==1000
ret1과 ret2의 넓이가 같다.
ret1가 ret보다 넓이가 작지 않다.
728x90
반응형
728x90
반응형
'프로그래밍 > C++' 카테고리의 다른 글
가상함수, 순수가상함수, 추상클래스 (0) | 2023.02.24 |
---|---|
상속 (0) | 2023.02.23 |
프랜드 (0) | 2023.02.21 |
static 수명이 길다 (0) | 2023.02.21 |
구조체도 클래스이다. (0) | 2023.02.20 |