판다코딩 c++ 생성자와 소멸자

개발자는엉금엉금·2022년 9월 21일
0

🤔acquire함수 대신 생성자를 이용하여 객체를 만들어보자.

💻stock.h

#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

  • public에서 class명(param1,param2...)로 선언가능하다

    소멸자는 객체가 소멸되거나 프로그램이 종료될 때 자동으로 호출된다.

💻function부분

#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;

}

  • Stock이라는 네임스페이스를 설정해줘야 class불러올 수 있음

💻main부분

#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;
}

  • (1)Stock temp = Stock("Panda", 100, 1000);
    (2)Stock temp2("Panda", 100, 1000);으로 객체 생성가능

    (2)가 편하니까 이걸로 익숙해지자

  • c++는 암묵적으로 디폴트 생성자를 만듦

temp = { "Coding",200,1000 };로 생성자를 재설정했기 때문에 클래스가 소멸되었다고 문구가 뜸

0개의 댓글