전체 코드
#include <iostream>
using namespace std;
class Apples {
private: // 클래스 내에서만 접근 가능
string name; // 사과 농장
int qty; // 사과 개수
float price; // 사과 한 개 가격
double total_pr;
void set_total() { total_pr = qty * price; }
public: // 클래스 외부에서 접근 가능
// public의 함수를 통해서만 private 값에 접근 가능 -> 데이터 은닉 : 데이터 직접 접근 막음
void acquire(string, int, float);
void buy(int, float);
void sell(int, float);
void show();
Apples();
~Apples();
};
void Apples::acquire(string fn, int n, float pr) { // 맨처음 사과 값
name = fn;
qty = n;
price = pr;
set_total();
}
void Apples::buy(int n, float pr) { // 사과 구매
qty += n;
price = pr;
set_total();
}
void Apples::sell(int n, float pr) { // 사과 판매
qty -= n;
price = pr;
set_total();
}
void Apples::show() {
cout << "사과 농장 : " << name << endl;
cout << "사과 개수 : " << qty << endl;
cout << "사과 한개 가격 : " << price << endl;
cout << "총 사과 가격 : " << total_pr << endl;
cout << endl;
}
Apples::Apples() { // 생성자
}
Apples::~Apples() { // 소멸자
}
int main() {
Apples A;
A.acquire("farm A", 10, 500);
A.show();
A.buy(15, 1000);
A.show();
A.sell(5, 100);
A.show();
return 0;
}
<출력>
사과 농장 : farm A
사과 개수 : 10
사과 한개 가격 : 500
총 사과 가격 : 5000
사과 농장 : farm A
사과 개수 : 25
사과 한개 가격 : 1000
총 사과 가격 : 25000
사과 농장 : farm A
사과 개수 : 20
사과 한개 가격 : 100
총 사과 가격 : 2000
분할 컴파일 적용 후
Apples.h
#ifndef APPLES
#define APPLES
#include <iostream>
using namespace std;
class Apples {
private: // 클래스 내에서만 접근 가능
string name; // 사과 농장
int qty; // 사과 개수
float price; // 사과 한 개 가격
double total_pr;
void set_total() { total_pr = qty * price; }
public: // 클래스 외부에서 접근 가능
// public의 함수를 통해서만 private 값에 접근 가능 -> 데이터 은닉 : 데이터 직접 접근 막음
void acquire(string, int, float);
void buy(int, float);
void sell(int, float);
void show();
Apples();
~Apples();
};
#endif
메인 c++ 파일
#include "Apples.h"
int main() {
Apples A;
A.acquire("farm A", 10, 500);
A.show();
A.buy(15, 1000);
A.show();
A.sell(5, 100);
A.show();
return 0;
}
함수 c++ 파일
#include "Apples.h"
void Apples::acquire(string fn, int n, float pr) { // 맨처음 사과 값
name = fn;
qty = n;
price = pr;
set_total();
}
void Apples::buy(int n, float pr) { // 사과 구매
qty += n;
price = pr;
set_total();
}
void Apples::sell(int n, float pr) { // 사과 판매
qty -= n;
price = pr;
set_total();
}
void Apples::show() {
cout << "사과 농장 : " << name << endl;
cout << "사과 개수 : " << qty << endl;
cout << "사과 한개 가격 : " << price << endl;
cout << "총 사과 가격 : " << total_pr << endl;
cout << endl;
}
Apples::Apples() { // 생성자
}
Apples::~Apples() { // 소멸자
}
728x90
'c++ 기초' 카테고리의 다른 글
22) this 포인터 (0) | 2025.01.04 |
---|---|
21) 생성자, 소멸자 (0) | 2025.01.04 |
19) 분할 컴파일 (0) | 2025.01.02 |
18) 함수 템플릿 (0) | 2025.01.01 |
17) 함수 오버로딩 (0) | 2025.01.01 |