🤔acquire함수 대신 생성자를 이용하여 객체를 만들어보자.
#ifndef STOCK
#define STOCK
#include <iostream>
using namespace std;
class Stock
{
private:
string name;
int shares;
float share_val;
double total_val;
void set_total() { total_val = shares * share_val; }
public:
void buy(int, float);
void sell(int, float);
void update(float);
void show();
Stock(string, int, float);//생성자를 매개변수로 선언
Stock();//디폴트 생성자
~Stock();//소멸자
};
#endif
소멸자는 객체가 소멸되거나 프로그램이 종료될 때 자동으로 호출된다.
#include "stock.h"
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();
}
Stock::Stock(string co, int n, float pr)
{
name = co;
shares = n;
share_val = pr;
set_total();
}
Stock::Stock()
{
name = "";
shares = 0;
share_val = 0;
set_total();
}
Stock::~Stock()
{
cout << name << "클래스가 소멸되었습니다.\n";
}
void Stock::show() {
cout << "주식명:" << name << endl;
cout << "주식 수:" << shares << endl;
cout << "주가:" << share_val << endl;
cout << "주식 총 가치:" << total_val << endl;
}
#include "stock.h"
int main()
{
cout << "생성자를 이용해 객체 생성\n";
Stock temp{ "Panda",100,1000};
cout << "디폴트 생성자를 이용하여 객체 생성\n";
Stock temp2;
cout << "temp와 temp2를 출력\n";
temp.show();
temp2.show();
cout << "생성자를 이용하여 temp 내용 재설정\n";
temp = { "Coding",200,1000 };
cout << "재설성된 temp 출력\n";
temp.show();
return 0;
}
(2)가 편하니까 이걸로 익숙해지자
temp = { "Coding",200,1000 };
로 생성자를 재설정했기 때문에 클래스가 소멸되었다고 문구가 뜸