연습문제 1: 은행 계좌 클래스
다음 요구사항에 맞는 BankAccount 클래스를 작성하시오:
- 계좌번호(accountNumber), 소유자 이름(ownerName), 잔액(balance)을 private 멤버변수로 가짐
- 각 멤버변수에 대한 getter와 setter 함수 구현
- 입금(deposit)과 출금(withdraw) 기능 구현 (출금은 잔액이 충분할 때만 가능)
- 계좌 정보 출력 함수(printInfo) 구현
#include <iostream>
#include <string>
using namespace std;
class BankAccount {
public:
// 기본생성자 // 생성자는 클래스 이름과 동일한 이름을 가진다.
// 멤버변수에 기본값들을 넣어주자. // 생성자는 반환형을 적지 않는다.
BankAccount() {
accountNumber = 0;
ownerName = "이름없음";
balance = 0;
}
// 매개변수가 있는 생성자 - 생성자를 또 만드는 이유는
//객체를 만들 때 상황에 따라 여러가지 방식으로 초기화 하고싶기 때문이다.
// 이 경우는 객체를 만들면서 동시에 필요한 모든 초기 값을 제공하고 싶을 때 사용한다.
BankAccount(long accNum, string name, int initialBalance) { // 변수이름은 camelCase
accountNumber = accNum;
ownerName = name;
balance = initialBalance;
}
// Getter 함수들 - private 멤버 변수에 저장된 값을 읽어올 때 사용한다.
long getAccountNumber() { return accountNumber; }
string getOwnerName() { return ownerName; }
int getBalane() { return balance; }
// Setter 함수들 - private 멤버 변수의 값을 설정하거나 바꿀 때 사용한다.
void setAccountNumber(long accNum) { accountNumber = accNum; }
void setOwnerName(string name) { ownerName = name; }
//입금 함수
bool deposit(int amount) {
if (amount > 0) {
balance += amount;
return true;
}
return false; // 양수일때만 입금이 가능한 조건
}
//출금 함수
bool withdraw(int amount) {
if (balance >= amount && amount > 0) {
balance -= amount;
return true;
}
return false; // 잔액부족. 양수 금액만 출금 가능
}
//계좌 정보 출력 함수
void printInfo() {
cout << "계좌번호 : " << accountNumber << endl;
cout << "예금주 : " << ownerName << endl;
cout << "잔액 : " << balance << "원" << endl;
}
private: // 멤버변수
long accountNumber; // 계좌번호
string ownerName; // 예금주
int balance; // 잔액
};
int main() {
long accountNum;
string name;
int balance;
int amount;
//계좌 생성 -- 객체 생성!!
cout << "계좌번호, 이름, 잔액을 입력하세요" << endl;
cin >> accountNum >> name >> balance;
BankAccount myAccount(accountNum, name, balance);
// 계좌 정보 출력
cout << "=====계좌 생성=====" << endl;
myAccount.printInfo();
//입금하기
bool depositSuccess = false;
while (!depositSuccess) { // 성공할 때까지 반복
cout << "======입금할 금액을 입력하세요 ====" << endl;
cin >> amount;
depositSuccess = myAccount.deposit(amount);
if (depositSuccess) {
cout << "======" << amount << "원 입금 완료! =====" << endl;
myAccount.printInfo();
}
else {
cout << "====입금 실패! 다시 시도해주세요====" << endl;
}
}
//출금
bool withdrawSuccess = false;
while (!withdrawSuccess) { // 성공할 때까지 반복
cout << "======출금할 금액을 입력하세요 ====" << endl;
cin >> amount;
withdrawSuccess = myAccount.withdraw(amount);
if (withdrawSuccess) {
cout << "======" << amount << "원 출금 완료! =====" << endl;
myAccount.printInfo();
}
else {
cout << "====출금 실패! 다시 시도해주세요====" << endl;
}
}
return 0;
}
클래스 구성 요약 정리
class BankAccount {
public: // 🎁 외부에서 접근 가능한 '인터페이스'
// 1. 생성자 (Constructors) - 객체가 태어날 때 초기화해주는 역할!
// 맨 위에 두는 건 '객체를 어떻게 만들 수 있나?'를 제일 먼저 보여주기 위함.
BankAccount() { /* 기본 초기화 */ }
BankAccount(long accNum, string name, int initialBalance) { /* 맞춤 초기화 */ }
// 2. Getter/Setter 함수 (Accessors/Mutators) - private 데이터에 접근할 수 있는 통로!
// 생성자 다음에 두는 건 데이터를 보고 설정하는 기본적인 방법을 보여줌.
long getAccountNumber() { return accountNumber; }
void setOwnerName(string name) { ownerName = name; }
int getBalance() { return balance; } // balance는 setter가 없는 경우도 많다!
// 3. 다른 멤버 함수 (Other Member Functions) - 객체가 할 수 있는 핵심 기능!
// deposit, withdraw, printInfo 등 객체의 '행동'을 정의.
bool deposit(int amount) { /* ... */ }
bool withdraw(int amount) { /* ... */ }
void printInfo() { /* ... */ }
private: // 🔒 외부에서 직접 접근 불가능한 '내부 구현'
// 1. 멤버 변수 (Member Variables) - 객체의 '상태'와 '데이터'를 담아두는 곳!
// 얘네들을 private으로 두는 게 '정보 은닉'이라는 개념.
// 외부에서 함부로 건드리지 못하게 해서 객체의 무결성을 지킴.
long accountNumber;
string ownerName;
int balance;
// (필요하다면) 2. Private 헬퍼 함수
// 복잡한 작업을 쪼개서 내부에서만 쓰는 함수들을 여기에 두기도 함.
};
연습문제 2: 도서 관리 클래스
다음 요구사항에 맞는 Book 클래스를 작성하시오:
- 책 제목(title), 저자(author), 출판연도(year), 대출 상태(isBorrowed) 멤버변수를 private으로 선언
- 모든 멤버변수에 대한 getter와 setter 함수 구현
- 대출(borrow)과 반납(returnBook) 기능 구현
- 생성자를 통해 책 정보 초기화
- 책 정보를 문자열로 반환하는 함수(getInfo) 구현
'C++ 공부' 카테고리의 다른 글
| C++언어 기초 - 6. 템플릿의 개념 (0) | 2025.08.26 |
|---|---|
| C++언어 기초 - 5. 자원 관리하기 (6) | 2025.08.26 |
| C++언어 기초 - 4. 객체지향 프로그래밍 (0) | 2025.08.21 |
| C++에서 char 배열과 std::string의 차이점 (0) | 2025.08.21 |
| C++언어 기초 - 3. Class의 개념 (0) | 2025.08.21 |