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 buy(int, float);
void sell(int, float);
void show();
Apples(string, int, float);
Apples(); // 힘수 오버로딩, 매개변수 없는 함수
~Apples();
};
#endif
메인 c++ 파일
#include "Apples.h"
int main() {
cout << "생성자 이용 객체 생성\n";
Apples A("farm A", 10, 500); // ver2 Apples A("farm B", 10, 500);
cout << "디폴트 생성자 이용 객체 생성\n";
Apples B; // 매개변수 없는 함수 선언 가능
cout << "A를 B에 대입\n";
B = A;
cout << endl;
cout << "<A> \n";
A.show();
cout << "<B> \n";
B.show();
cout << endl;
cout << "생성자를 이용해 A 재설정\n";
A = Apples("farm B", 20, 1000);
cout << endl;
cout << "<재설정된 A> \n";
A.show();
return 0;
}
함수 c++ 파일
#include "Apples.h"
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(string fn, int n, float pr) {
name = fn;
qty = n;
price = pr;
set_total();
}
Apples::Apples() { // 매개변수 없는 함수
name = "";
qty = 0;
price = 0;
set_total();
}
Apples::~Apples() {
cout << name << " Class 소멸됨\n";
}
<출력>
<A>
사과 농장 : farm A
사과 개수 : 10
사과 한개 가격 : 500
총 사과 가격 : 5000
<B>
사과 농장 : farm A
사과 개수 : 10
사과 한개 가격 : 500
총 사과 가격 : 5000
생성자를 이용해 A 재설정
farm B Class 소멸됨
<재설정된 A>
사과 농장 : farm B
사과 개수 : 20
사과 한개 가격 : 1000
총 사과 가격 : 20000
farm A Class 소멸됨
farm B Class 소멸됨
728x90
'c++ 기초' 카테고리의 다른 글
23) 클래스 배열 (0) | 2025.01.05 |
---|---|
22) this 포인터 (0) | 2025.01.04 |
20) 클래스 (0) | 2025.01.03 |
19) 분할 컴파일 (0) | 2025.01.02 |
18) 함수 템플릿 (0) | 2025.01.01 |