사자자리
[C++] 클래스 생성자와 소멸자 본문
생성자
- 디폴트 생성자: Stock();
- 생성자 오버로딩: Stock(string co, int n, float pr);
- 생성자를 따로 정의하지 않으면, 컴파일러가 자동으로 디폴트 생성자를 만든다.
- 하지만 생성자를 하나라도 오버로딩한다면, 디폴트 생성자는 개발자가 직접 작성해야 한다.
소멸자
~Stock();
- 소멸자를 따로 정의하지 않으면, 컴파일러가 자동으로 디폴트 소멸자를 만든다.
- 클래스를 소멸하는 일만 할 수 있다.
//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 // !STOCK
//func.cpp
#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();
}
void Stock::show() {
cout << "회사 명 : " << name << endl;
cout << "주식 수 : " << shares << endl;
cout << "주가 : " << share_val << endl;
cout << "주식 총 가치 : " << total_val << endl;
}
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";
}
//main.cpp
#include <iostream>
#include "Stock.h"
int main() {
cout << "생성자를 이용해 객체 생성\n";
Stock temp("Panda", 100, 1000); //Stock형 변수를 선언하는 방법 1
cout << "디폴트 생성자를 이용하여 객체 생성\n";
Stock temp2; //디폴트 생성자를 선언해서, 명시적으로 초기화를 하지 않고도 변수를 선언할 수 있다.
cout << "temp와 temp2 출력\n";
temp.show();
temp2.show();
cout << "생성자를 이용하여 temp 내용 재설정\n";
temp = Stock("Coding", 200, 1000); //Stock형 변수를 선언하는 방법 2
cout << "재설정된 temp 출력\n";
temp.show();
return 0;
}
'C++ > C++ 이론' 카테고리의 다른 글
[C++] 연산자 오버로딩 (0) | 2022.08.24 |
---|---|
[C++] this 포인터와 클래스 객체 배열 (0) | 2022.08.17 |
[C++] 추상화와 클래스 (0) | 2022.08.17 |
[C++] 분할 컴파일: #ifndef & #endif (0) | 2022.08.17 |
[C++] 함수의 활용 (0) | 2022.08.05 |
Comments