-
[C++] desk_lamp.cpp (객체와 클래스에 대한 이해)C++/clone code 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;
}
실행결과
'C++ > clone code' 카테고리의 다른 글
[C++] market.cpp (객체와 클래스에 대한 이해) (0) 2022.06.28 [C++] 계좌 잔액 조회하기.cpp (객체와 클래스에 대한 이해) (0) 2022.06.28 [C++] find_max_n_min.cpp 최댓값, 최솟값 구하는 프로그램(배열 활용) (0) 2022.05.23 [C++] sum_matrix.cpp 3x3 행렬 덧셈 프로그램 (0) 2022.05.23 [C++] 2차원 배열의 이해(two dimensional array) (0) 2022.05.23