판다코딩 c++ 클래스 연습

Icarus<Wing>·2022년 9월 20일
0

💻stock.h

#ifndef STOCK
#define STOCK
#include <iostream>

using namespace std;
//주식 프로그램:주식 선언,사고,팔고,가격을 업데이트해주고,보여주는
//public에 void acuire,buy,sell,update,show 함수를 선언한다
class Stock
{
private:
	string name;
	int shares;
	float share_val;
	double total_val;
	void set_total() { total_val = shares * share_val; }
	//코드의 가독성을 위해 이렇게 작성
	//double로 하고 return total_val로 해도 같은 결과나옴
	

public:
	void acquire(string, int, float);
	void buy(int, float);
	void sell(int, float);
	void update(float);
	void show();
};
#endif

💻main함수부분

#include "stock.h"
int main()
{
	Stock temp;
	temp.acquire("Panda", 100, 1000);
	temp.show();
	temp.buy(50, 500);
	temp.show();
	temp.sell(30, 2000);
	temp.show();
	
	return 0;
}

💻function 부분

#include "stock.h"
//public함수를 통해 private에 접근한다 & ::연산자를 통해 Stock private에 접근
void Stock::acquire(string co, int n, float pr)//Stock이라는 네임스페이스 범위 결정
{
	name = co;
	shares = n;
	share_val = pr;
	set_total();
}

void Stock::buy(int n, float pr)
{
	shares += n;
	share_val = pr;
	set_total();
}
void Stock::sell(int n, float pr)
{
	shares -= n;
	share_val = pr;
	set_total();
}
void Stock::update(float pr)
{
	share_val = pr;
	set_total();
}

void Stock::show() {
	cout << "주식명:" << name << endl;
	cout << "주식 수:" << shares << endl;
	cout << "주가:" << share_val << endl;
	cout << "주식 총 가치:" << total_val << endl;

}

💡set_total()함수를 total_val()로 작성했는데, 변수명과 함수명이 동일하면 에러가 나기때문에 주의합시다.

profile
모든 코드에는 이유가 있기에 원인을 파악할 때까지 집요하게 탐구하는 것을 좋아합니다.

0개의 댓글