반응형
다음 main()에서 Color 클래스는 3요소(빨강, 초록, 파랑)로 하나의 색을 나타내는 클래스이다. (4장 실습 문제 1번 참고). + 연사자로 색을 더하고, == 연사자로 색을 비교하고자 한다. 실행결과를 참고하여 Color 클래스와 연산자, 그리고 프로그램을 완성하라.
int main() {
Color red(255, 0, 0), blue(0, 0, 255), c;
c = red + blue;
c.show();
Color fuchsia(255, 0, 255);
if (c == fuchsia)
cout << "보라색 맞음";
else
cout << "보라색 아님";
}
결과
255 0 255
보라색 맞음
1. + 와 == 연사자를 Color 클래스의 멤버 함수로 구현하라.
#include<iostream>
using namespace std;
class Color {
int r, g, b;
public:
Color() {};
Color(int r, int g, int b) { this->r = r; this->g = g; this->b = b; };
void show();
Color operator+(Color b);
bool operator==(Color f);
};
Color Color::operator+(Color b)
{
Color a;
a.r = this->r + b.r;
a.g = this->g + b.g;
a.b = this->b + b.b;
return a;
}
bool Color::operator==(Color f)
{
if (this->r == f.r && this->g == f.g && this->b == b)
return true;
return false;
}
int main() {
Color red(255, 0, 0), blue(0, 0, 255), c;
c = red + blue;
c.show();
Color fuchsia(255, 0, 255);
if (c == fuchsia)
cout << "보라색 맞음";
else
cout << "보라색 아님";
}
2. +와 == 연사자를 Color 클래스의 프렌드 함수로 구현하라.
#include<iostream>
using namespace std;
class Color {
int r, g, b;
public:
Color() {};
Color(int r, int g, int b) { this->r = r; this->g = g; this->b = b; };
void show();
friend Color operator+(Color a, Color b);
friend bool operator==(Color a, Color b);
};
void Color::show()
{
cout << this->r << " " << this->g << " " << this->b << endl;
}
Color operator+(Color a, Color b)
{
Color c;
c.r = a.r + b.r;
c.g = a.g + b.g;
c.b = a.b + b.b;
return c;
}
bool operator==(Color a, Color b)
{
if (a.r == b.r && a.g == b.g && a.b == b.b)
return true;
return false;
}
int main() {
Color red(255, 0, 0), blue(0, 0, 255), c;
c = red + blue;
c.show();
Color fuchsia(255, 0, 255);
if (c == fuchsia)
cout << "보라색 맞음";
else
cout << "보라색 아님";
}
오류 또는 수정 사항 궁금한 점 있으시면 댓글로 남겨주세요.
반응형
'명품C++프로그래밍' 카테고리의 다른 글
명품 C++ Programming 실습문제 7장 7번 (0) | 2021.05.20 |
---|---|
명품 C++ Programming 실습문제 7장 6번 (0) | 2021.05.20 |
명품 C++ Programming 실습문제 7장 4번 (0) | 2021.05.20 |
명품 C++ Programming 실습문제 7장 3번 (0) | 2021.05.20 |
명품 C++ Programming 실습문제 7장 2번 (0) | 2021.05.20 |