생성자 - triangle class

Triangle

실습 예제

ch07ex9_삼각형클래스.cpp

Triangle class

instance variable int height char shape instance method getter setter displayShape()

삼각형 클래스를 만들어 봅시다. 인스턴스 변수는 private하여 getter, setter를 통해 접근 가능합니다. displayShape()은 높이 만큼 shape모양으로 직각 삼각형을 출력합니다.

#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::string;

class Triangle
{
public:
	Triangle(int h, char ch)
	{
		setHeight(h);
		setShape(ch);
	}
	inline void setHeight(int h)
	{
		if (h > 0) height = h;
	}
	inline void setShape(char ch)
	{
		shape = ch;
	}
	inline int getHeight() const
	{
		return height;
	}
	inline char getShape() const
	{
		return shape;
	}
	void displayShape() const;

private:
	int height = 1;
	char shape = '\0';
};

int main()
{
	Triangle t1(5, '*');
	t1.displayShape();

	int h;
	char sh;
	cout << "높이: ";
	cin >> h;
	t1.setHeight(h);
	cout << "모양: ";
	cin >> sh;
	t1.setShape(sh);
	t1.displayShape();

	cout << "삼각형의 모양은 " << t1.getShape() << "입니다." << endl;
	cout << "삼각형의 높이는 " << t1.getHeight() << "입니다." << endl;

	return 0;
}

void Triangle::displayShape() const
{
	for (int i = 0; i < height; i++)
	{
		for (int j = 0; j <= i; j++)
		{
			cout << shape;
		}
		cout << endl;
	}
}

실습 문제

ch07lab8_RGB.cpp

RGB Color 클래스를 작성하시오.

RGB 색상은 Red, Green, Blue 세 값으로 이루어진다. 각 값은 0 ~ 255 범위의 정수이다.

아래 조건을 모두 만족하는 클래스를 작성하시오.


1. 멤버 변수 (private)

  • int r : Red 값

  • int g : Green 값

  • int b : Blue 값


2. 생성자 (public)

  • _r, _g, _b 값을 각각 r, g, b에 저장한다.

  • 만약 전달된 값이 0 미만 또는 255 초과라면 → 해당 색상 값을 0으로 자동 보정한다.


3. 멤버 함수 (public)

void display() const


4. main()

Last updated