C++/clone code

[C++] desk_lamp.cpp (객체와 클래스에 대한 이해)

year.number 2022. 6. 28. 17:50

Power C++ p.387

[목표] 책상에 있는 램프의 상태를 출력한다.

 

#include <iostream>
#include <string>

using namespace std;

class DeskLamp {
private:
	bool isOn;

public:
	void turnOn();
	void turnOff();
	void print();
};

void DeskLamp::turnOn() {
	isOn = true;
}

void DeskLamp::turnOff() {
	isOn = false;
}

void DeskLamp::print() {
	if (isOn == true)
		cout << "불이 켜졌습니다." << endl;
	else if (isOn == false)
		cout << "불이 꺼졌습니다." << endl;
}

int main() {

	DeskLamp lamp;
	
	lamp.turnOn();
	lamp.print();
	lamp.turnOff();
	lamp.print();

	return 0;
}

 


Key Point 

1. 클래스를 정의한다 -> 객체를 생성한다 -> 메세징한다

2. 조건문에서 대입 연산자(=)가 아닌 관계 연산자(==)를 사용해야 함에 유의한다

 

void DeskLamp::print() {
if (isOn == true)
cout << "불이 켜졌습니다." << endl;
else if (isOn == false)
cout << "불이 꺼졌습니다." << endl;
}

 


실행결과