728x90

정적 할당

- stack 과 data영역에 할당 될 메모리의 크기는 컴파일 타임에 결정됨

 

동적 할당 

- heap 영역은 프로그램이 실행되는 중간에 메모리를 할당하고 해제할 수 있는 공간이 결정된다

 

동적할당 하는법

#include <iostream>

using namespace std;


int main() {
	int num = 200;

	//int* pnum; //포인터 변수 선언: 주소만 가질수 있다
	int* pnum = new int(100); //자료형으로 변수 만들기 new;동적할당

	cout << num << endl;
	cout << pnum << endl;//주소 프린트
	cout << *pnum << endl;//변수 안의 저장된 주소를 찾아가서 값을 처리

	*pnum = 300;
	cout << pnum << endl;
	cout << *pnum << endl;

	delete pnum;
}

같은 주소에 새로운 값만 할당

 

 

 

배열 동적할당: 단위가 큰 배열은 동적할당이 빠름

#include <iostream>

using namespace std;


int main() {
	cout << "integer number: ";
	int n = 0;
	cin >> n;
	if (n < -0) return 0;
	int* p = new int[n];
	if (!p)
	{
		cout << "cant get memory" << endl;
		return 0;
	}
	for (int i = 0; i < n; i++) {
		cout << i + 1 << "th integer";
		cin >> p[i];
	}
	int sum = 0;
	for (int i = 0; i < n; i++)
	{
		sum += p[i];
	}
	cout << "sum of all number: " << sum << endl;
	delete[] p;
}

 

객체 만드는 동적할당

#include <iostream>

using namespace std;


class student {

private:
	string name;
	int grade;
	int room;

public:
	student()
	{
		cout << "-------------->student 생성자<---------------" << endl;
	}

	void setName(string n) {
		name = n;
	}
	void setGrade(int g) {
		grade = g;
	}
	void setRoom(int r) {
		room = r;
	}

	string getName() {
		return name;
	}
	int getGrade() {
		return grade;
	}
	int getRoom() {
		return room;
	}
};

int main() {
	student stu1;
	stu1.setName("Emily");
	stu1.setGrade(12);
	stu1.setRoom(3);

	cout << &stu1 << endl;
	cout << stu1.getName() << endl;
	cout << stu1.getGrade() << endl;
	cout << stu1.getRoom() << endl;

	cout << "+++++++++++++++++++++++++++++++++++++++++++++" << endl;
}

 

동적할당 정적할당 차이

#include <iostream>

using namespace std;

#include <iostream>

using namespace std;


class student {

private:
	string name;
	int grade;
	int room;

public:
	student()
	{
		cout << "-------------->student 생성자<---------------" << endl;
	}

	void setName(string n) {
		name = n;
	}
	void setGrade(int g) {
		grade = g;
	}
	void setRoom(int r) {
		room = r;
	}

	string getName() {
		return name;
	}
	int getGrade() {
		return grade;
	}
	int getRoom() {
		return room;
	}
};

int main() {

	/* 정적 할당
	student stu1;
	stu1.setName("Emily");
	stu1.setGrade(12);
	stu1.setRoom(3);

	cout << &stu1 << endl;
	cout << stu1.getName() << endl;
	cout << stu1.getGrade() << endl;
	cout << stu1.getRoom() << endl;

	cout << "-------------->student 소멸자<---------------" << endl;
	*/

	//동적 할당
	student* ps = nullptr;
	ps = new student;

	ps->setName("Layla");
	ps->setGrade(9);
	ps->setRoom(1);

	cout << ps->getName() << endl;
	cout << ps->getGrade() << endl;
	cout << ps->getRoom() << endl;

	delete ps;

	cout << "-------------->student 소멸자<---------------" << endl;

	student* stu = new student;

	stu->setName("Carbon");
	stu->setGrade(11);
	stu->setRoom(6);

	cout << stu->getName() << endl;
	cout << stu->getGrade() << endl;
	cout << stu->getRoom() << endl;

	delete stu;
	cout << "-------------->student 소멸자<---------------" << endl;
}
728x90

'언어는 과-학인가요? > C++' 카테고리의 다른 글

멤버 이니셜라이저 (Member initializer) 초기화  (0) 2020.11.21
Foodgame c++  (0) 2020.11.14
orangebox  (0) 2020.11.14
함수로 값바꾸기  (0) 2020.11.14
Protected, Private, Public 함수 : 이동시키기  (0) 2020.10.31
728x90

멤버 이니셜라이저 (Member initializer)

: 만듦과 동시에 초기화

#include <iostream>

using namespace std;

class AAA {
private:
	int num;
public:

	AAA(int a) :num(10) {} //:=초기화

	void show_num() {
		cout << "num 변수값= " << num << endl;
	}
};

int main() {
	AAA aaa(10);
	aaa.show_num();

	return 0;
}

초기화 하고 잘 들어감

 

생성자 대입 

#include <iostream>

using namespace std;

class AAA {
private:
	int num;
public:
	
	AAA(int a) {
		num = a;
	}

	void show_num() {
		cout << "num 변수값= " << num << endl;
	}
};

int main() {
	AAA aaa(30);
	aaa.show_num();

	return 0;
}

 

const 맴버일때 initialize

#include <iostream>

using namespace std;

class AAA {
private:
	const int num;
	//클래스내의 멤버 변수에 const는 고정되어있음
	//새로운 값을 생성자 함수로 대입할 수 없다
	//이미 객체가 생성되었을때 쓰레기값으로 초기화되어있음

public:

	AAA(int a) :num(a) {} //:=초기화

	void show_num() {
		cout << "num 변수값= " << num << endl;
	}
};

int main() {
	AAA aaa(30);
	aaa.show_num();

	return 0;
}

생성 필요없이 바로초기화 

 

초기화 안하면 일어나는일 

#include <iostream>

using namespace std;

class Time {
public:
	int h;
	int m;
	int s;

	Time() {
		h = 0;
		m = 0;
		s = 0;
	}

	Time(int _h) {
		h = _h;
	}

	Time(int _h, int _m) {
		h = _h;
		m = _m;
	}

	Time(int _h, int _m, int _s) {
		h = _h;
		m = _m;
		s = _s;
	}

	void showTime() {
		cout << h << "hour:" << m << "minute:" << s << "seconds" << endl;
	}


};

int main() {
	//생성자 함수 내에서 시:분:초 값 0으로 대입
	Time t1;
	t1.showTime();

	//시간만 입력 >생성자 함수
	Time t2(3);
	t2.showTime();

	//시, 분만 입력> 생성자함수
	Time t3(5, 16);
	t3.showTime();

	//시,분,초만 입력 >생성자함수
	Time t4(1, 30, 40);
	t4.showTime();

}

쓰레기값이 들어감

#include <iostream>

using namespace std;

class Time {
public:
	int h;
	int m;
	int s;

	/*Time() {
		h = 0;
		m = 0;
		s = 0;
	}*/

	Time() :h(0), m(0), s(0) {}//초기화 하는걸 넣어줌

	Time(int _h) : Time()
	{
		h = _h;
	}

	Time(int _h, int _m) : Time(_h)
	{
		m = _m;
	}

	Time(int _h, int _m, int _s) : Time(_h,_m)
	{
		s = _s;
	}

	void showTime() {
		cout << h << "hour:" << m << "minute:" << s << "seconds" << endl;
	}


};

int main() {
	//생성자 함수 내에서 시:분:초 값 0으로 대입
	Time t1;
	t1.showTime();

	//시간만 입력 >생성자 함수
	Time t2(3);
	t2.showTime();

	//시, 분만 입력> 생성자함수
	Time t3(5, 16);
	t3.showTime();

	//시,분,초만 입력 >생성자함수
	Time t4(1, 30, 40);
	t4.showTime();

}

초기화를 해봄

 

초기화의 중요성

#include <iostream>

using namespace std;

class Time {
public:
	int h;
	int m;
	int s;

	Time(int _h, int _m, int _s) {
		this->h = _h; //this: 상속개념
		this->m = _m;
		this->s = _s;
	}
	//Time(int _h,int _m, int _s):h(_h),m(_m),s(_s){} 로도 표현가능

	void showTime() {
		cout << h << "hour:" << m << "minute:" << s << "seconds" << endl;
	}
};

	class TimeTwo : public Time {
		public:
			TimeTwo(int _h, int _m, int _s) :Time(h, m, s) {}
	};

	

int main() {
	Time t1(3, 3, 3);
	t1.showTime();
	TimeTwo tt1(5, 40, 20);
	tt1.showTime();

}

이러면 ㅅㅅ2에 쓰레기값 들어감

#include <iostream>

using namespace std;

class Time {
public:
	int h;
	int m;
	int s;

	Time(int _h, int _m, int _s) {
		this->h = _h; //this: 상속개념
		this->m = _m;
		this->s = _s;
	}
	//Time(int _h,int _m, int _s):h(_h),m(_m),s(_s){} 로도 표현가능

	void showTime() {
		cout << h << "hour:" << m << "minute:" << s << "seconds" << endl;
	}
};

	class TimeTwo : public Time {
		public:
			TimeTwo(int _h, int _m, int _s) :Time(8, 8, 8) {}
	};

	

int main() {
	Time t1(3, 3, 3);
	t1.showTime();
	TimeTwo tt1(5, 40, 20);
	tt1.showTime();

}

그래서 직접 넣어줘보자

잘 들어감

728x90

'언어는 과-학인가요? > C++' 카테고리의 다른 글

동적변수와 정적변수  (0) 2020.11.21
Foodgame c++  (0) 2020.11.14
orangebox  (0) 2020.11.14
함수로 값바꾸기  (0) 2020.11.14
Protected, Private, Public 함수 : 이동시키기  (0) 2020.10.31
728x90
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>

using namespace std;

class GameObject {
protected:
	int distance;
	int x, y;

public:
	GameObject(int startX, int startY, int distance)
	{
		this->x = startX; this->y = startY;
		this->distance = distance;
	}

	virtual ~GameObject() {};
	virtual void move() = 0;
	virtual char getShape() = 0;
	int getX() { return x; }
	int getY() { return y; }
	bool collide(GameObject* p) {
		if (this->x == p->getX() && this->y == p->getY())
			return true;
		else
			return false;
	}
};


class Human : public GameObject {
public:
	Human(int x, int y, int dis) :GameObject(x, y, dis) {}
	void move();
	char getShape() { return'H'; }
};


void Human::move()
{
	string key;
	for (;;) {
		cout << "left(a), down(s), up(w), right(d)" << endl;
		cin >> key;
		if (key == "a") {
			if (y != 0) {
				y -= distance;
				break;

			}
			else cout << "cant move" << endl;
		}
		else if (key == "s") {
			if (x != 19) {
				x += distance;
				break;
			}
			else cout << "cant move" << endl;
		}
		else if (key == "w") {
			if (x != 0) {
				x -= distance;
				break;
			}
			else cout << "cant move" << endl;
		}
		else if (key == "d") {
			if (y != 19) {
				y += distance;
				break;
			}
			else cout << "cant move" << endl;
		}
		else
			cout << "error" << endl;
	}
}

class Monster :public GameObject
{
public:
	Monster(int x, int y, int dis) :GameObject(x, y, dis) {
		srand((unsigned)time(0));
	}
	void move();
	char getShape() { return'M'; }

};

void Monster::move() {
	for (;;) {
		int n = rand() % 4;
		if (n == 0)
		{
			if (y > 1) {
				y -= distance;
				break;
			}
		}
		else if (n == 1)
		{
			if (x < 18)
			{
				x += distance;
				break;
			}
		}
		else if (n == 2)
		{
			if (x > 1)
			{
				x -= distance;
				break;
			}
		}
		else 
		{
			if (y < 18)
			{
				x += distance;
				break;
			}
		}
	}
 }

class Food :public GameObject {
public:
	Food(int x, int y, int dis) :GameObject(x, y, dis) {}
	void move();
	char getShape() { return'@'; }
};

void Food::move() {
	for (;;) {
		int n = rand() % 4;
		if (n == 0)
		{
			if (y != 0) {
				y -= distance;
				break;
			}
		}
		else if (n == 1)
		{
			if (x != 19)
			{
				x += distance;
				break;
			}
		}
		else if (n == 2)
		{
			if (x != 0)
			{
				x -= distance;
				break;
			}
		}
		else
		{
			if (y != 19)
			{
				x += distance;
				break;
			}
		}
	}
}

class Game
{
	string board[20][20];
	Human* h = new Human(0, 0, 1);
	Monster* m = new Monster(5, 7, 2);
	Food* f = new Food(8, 10, 1);

public: 
	Game() {
		srand((unsigned)time(0));
		cout << "Human food game start" << endl << endl;

		for (int i = 0; i < 20; i++)
		{
			for (int j = 0; j < 20; j++)
				board[i][j] = "-";
		}
	}
	~Game() {
		delete h; delete m; delete f;
	}

	void game();

	void clr1() {
		board[h->getX()][h->getY()] = "-";
		board[m->getX()][m->getY()] = "-";
	}

	void clr2()
	{
		board[f->getX()][f->getY()] = "-";
	}

	void setXY() {
		board[h->getX()][h->getY()] = h->getShape();
		board[m->getX()][m->getY()] = m->getShape();
		board[f->getX()][f->getY()] = f->getShape();

	}

	void show() {
		for (int i = 0; i < 20; i++) {
			for (int j = 0; j < 20; j++)
				cout << board[i][j];
			cout << endl;
		}
	}

};

void Game::game()
{
	int count = 0, gamecount = 0;
	for (;;)
	{
		setXY();
		show();
		clr1();
		h->move(); m->move();
		int n = rand();
		cout << endl;

		if (n % 2 == 0 && count < 2 && gamecount < -3) {
			clr2();
			f->move();
			++count;
		}

		if (gamecount > 3 && count < 2) {
			clr2();
			f->move();
			++count;
		}
		if (f->collide(h)) {
			setXY();
			board[f->getX()][f->getY()] = "H";
			show();
			cout << "Human is winner" << endl;
			break;
		}
		else if (h->collide(m)) {
			setXY();
			board[f->getX()][f->getY()] = "M";
			show();
			cout << "Monster is winner" << endl;
			break;
		}
		else if (f->collide(m)) {
			setXY();
			board[f->getX()][f->getY()] = "M";
			show();
			cout << "Monster is winner" << endl;
			break;
		}
		++gamecount;

		if ((gamecount % 5) == 0) {
			count = 0;
			gamecount = 0;
		}
	}
}

int main()
{
	Game* g = new Game;
	g->game();
	delete g;
	Game();
}
728x90
728x90
#include <iostream>
using namespace std;

class orangebox {
public:

	//생성자함수
	orangebox();
	//소멸자함수
	~orangebox();

	void add(int addorange);
	void del(int delorange);
	void empty();
	int gettotal();
	int gettotalkg();


private:
	int total;
	int total1;
	int delcount;


};

//생성자함수(누적변수)
orangebox::orangebox()
{
	total = 0; //상자에 담겨 있는 오렌지 총합계
	total1 = 0;// 상자에 담겨있는 오렌지 총합계의 총무게
}
orangebox::~orangebox()
{
	cout << "오렌지 상자 오브젝트 임무 끝" << endl;
}

int orangebox::gettotal()
{
	return total;
}

int orangebox::gettotalkg() {
	return total1;
}


void orangebox::add(int addorange) {
	total += addorange;
	total1 += addorange * 50;

	if (total >= 100)
	{
		total = 100;
		cout << "100개이상의 오렌지 개수를 입력하면 100개로 계산합니다: (매개 변수값)" << total << endl;
		cout << "상자속의 오렌지 총 무게는: " << total1 << endl;
		cout << endl;
	}
	else
	{
		cout << "상자속의 오렌지 개수:" << total << endl;
		cout << "오렌지총무게: " << total1 << endl;
		cout << "------------------------" << endl;
	}
}

void orangebox::empty()
{
	total = 0;
	cout << "empty 상자속 오렌지: " << total << endl;
}

void orangebox::del(int delorange)
{
	delcount = delorange;
	total -= delorange;
	total1 -= delorange * 50;
	cout << "상자속에서 꺼낸 오렌지의 개수는: " << delorange << endl;
	cout << "----------------------------" << endl;

	if (total < 0) empty();
}

int main() {
	orangebox myorangebox;
	myorangebox.empty();
	myorangebox.add(50);
	myorangebox.del(20);

	cout << endl;
	cout << "남은 오렌지 무게: " <<myorangebox.gettotal() << endl;
	cout << "남은 오렌지 총무게: " << myorangebox.gettotalkg() << endl;
	cout << "--------------------" << endl;
	return 0;
}
728x90

'언어는 과-학인가요? > C++' 카테고리의 다른 글

멤버 이니셜라이저 (Member initializer) 초기화  (0) 2020.11.21
Foodgame c++  (0) 2020.11.14
함수로 값바꾸기  (0) 2020.11.14
Protected, Private, Public 함수 : 이동시키기  (0) 2020.10.31
상속  (0) 2020.10.31
728x90
#include <iostream>
using namespace std;

class Car {

public:

	bool poweron;
	string colour;
	int wheel;
	int speed;
	bool wiperon;

	//생성자 호출 함수(객체가 만들어질때 초기화 시키는 함수)
	//반드시 클래스명과 같아야함

	Car() {
		poweron = true;
		colour = "red";
		wheel = 4;
		speed = 100;
		wiperon = false;
	}

	Car(bool po, string col, int whe, int spe, bool wip) {
		poweron = po;
		colour = col;
		wheel = whe;
		speed = spe;
		wiperon = wip;
	}


	void power() {
		poweron = !poweron;
	}

	void speedup() {
		speed++;
	}

	void speeddown() {
		speed--;
	}

	void wiper() {
		wiperon = !wiperon;
	}

};

int main() {
	Car mycar;

	mycar.poweron = true;
	mycar.colour = "red";
	mycar.wheel = 4;
	mycar.speed = 100;
	mycar.wiperon = true;

	cout << "mycar's status: " << mycar.poweron << endl;
	cout << "mycar's colour: " << mycar.colour << endl;
	cout << "mycar's wheel: " << mycar.wheel << endl;
	cout << "speed: " << mycar.speed << endl;
	cout << "wiper: " << mycar.wiperon << endl;
	cout << "-------------------------" << endl;

	Car mycar1;

	cout << "mycar1's status: " << mycar1.poweron << endl;
	cout << "mycar1's colour: " << mycar1.colour << endl;
	cout << "mycar1's wheel: " << mycar1.wheel << endl;
	cout << "mycar1's speed: " << mycar1.speed << endl;
	cout << "mycar1's wiper: " << mycar1.wiperon << endl;
	cout << "-------------------------" << endl;

	Car mycar2(true, "blue", 4, 200, false);
	cout << "mycar2's status: " << mycar2.poweron << endl;
	cout << "mycar2's colour: " << mycar2.colour << endl;
	cout << "mycar2's wheel: " << mycar2.wheel << endl;
	cout << "mycar2's speed: " << mycar2.speed << endl;
	cout << "mycar2's wiper: " << mycar2.wiperon << endl;
	cout << "-------------------------" << endl;

}
728x90

'언어는 과-학인가요? > C++' 카테고리의 다른 글

Foodgame c++  (0) 2020.11.14
orangebox  (0) 2020.11.14
Protected, Private, Public 함수 : 이동시키기  (0) 2020.10.31
상속  (0) 2020.10.31
생성자와 소멸자 (constructor and destructor)  (0) 2020.10.24
728x90
#include <iostream>

using namespace std;

class Point {
public:
	int x, y;

public:
	//생성자함수: 클래스를 객체화시킬때 값을 초기화 시키는 기능
	//생성자 함수는 반드시 클래스명하고 같아야 한다
	//함수를 오버로딩 시켜서 여러개의 인수 형태를 지정해서 초기화 가능
	Point();

	void moveLeft(); //좌표 왼쪽으로 이동시키는 함수
	void moveRight(); //좌표 오른쪽으로 이동시키는 함수
	void print(); //좌표 출력하는 함수

	
};

class childPoint : public Point
{
public:
	void moveUp();
	void moveDown();
};


//생성자 함수 구현
//객체 생성시 x좌표 50 y좌표 50

Point::Point() {
	x = 50;
	y = 50;
	print();
}

//왼쪽으로 이동하는 함수
void Point::moveLeft() {
	x = x - 1;
	print();
}

//오른쪽으로 이동하는 함수
void Point::moveRight() {
	y = y - 1;
	print();
}

void Point::print()
{
	cout << x << " " << y << endl;
}

void childPoint::moveUp() {
	x = x + 10;
	print();
}

void childPoint::moveDown() {
	y = y - 10;
	print();

}


int main() {

	Point p;
	childPoint cp;

	cout << "------------------" << endl;
	p.moveLeft();
	p.moveLeft();
	cout << "------------------" << endl;
	p.moveRight();
	p.moveRight();
	cout << "------------------" << endl;
	cp.moveUp();
	cp.moveUp();
	cout << "------------------" << endl;
	cp.moveDown();
	cp.moveDown();


	return 0;
}

#include <iostream>

using namespace std;

class PointOne {
public:
	PointOne()
	{
		cout << "PointOne 생성자임" << endl;
		cout << "==============================" << endl;

	}
	~PointOne()
	{
		cout << "PointOne 소멸자임" << endl;
		cout << "==============================" << endl;

	}

public:
	int one_pubx;

protected:
	int one_prox;

private:
	int one_prix;

public:
	void output() {
		cout << "public one pubx" << one_pubx << endl;
		cout << "public one prox" << one_prox << endl;
		cout << "public one prix" << one_prix << endl;

	}
};

class PointTwo :public PointOne {
public:
	PointTwo()
	{
		one_pubx = 1000;
		one_prox = 2000;
		//one_prix = 3000; 부모 클래스의 멤버 변수가 private이라서 
		cout << "PointTwo 생성자임\n" << endl;
	}

	~PointTwo()
	{
		cout << "PointTwo 소멸자임\n" << endl;
	}
};

int main() {
	PointOne p1;
	PointTwo p2;

	cout << "-----------------------" << endl;
	p1.output();
	cout << "-----------------------" << endl;
	p2.output();
	cout << "-----------------------" << endl;

	//부모 클래스로 만든 p1객체에서 값 지정
	p1.one_pubx = 500;
	//p1.one_prox=2000; main에서 접근안됨

	p2.one_pubx = 700;

	cout << "---------p1 객체 시작----------" << endl;
	p1.output();
	cout << "---------p1 객체 끝----------\n" << endl;

	cout << "---------p2 객체 시작----------" << endl; 
	p2.output();
	cout << "---------p2 객체 끝----------" << endl;
}

728x90

'언어는 과-학인가요? > C++' 카테고리의 다른 글

orangebox  (0) 2020.11.14
함수로 값바꾸기  (0) 2020.11.14
상속  (0) 2020.10.31
생성자와 소멸자 (constructor and destructor)  (0) 2020.10.24
객체 지향 프로그래밍 (OOP)  (0) 2020.10.24
728x90
#include <iostream>

using namespace std;

class parents {
public:
	//자식 클래스의 멤버 함수
	void pFunc() 
	{
		cout << "부모클래스" << endl;
	}

	//자식 클래스의 멤버 변수
	int pnum;
};

class ch1: public parents {
public:
	//자식 클래스의 멤버 함수
	void ch1Func()
	{
		cout << "자식클래스" << endl;
	}

	//자식 클래스의 멤버 변수
	int ch1num;
};

int main() {

	//클래스를 인스턴스화 시킨다
	//클래스 구조를 메모리에 그대로 만든다
	//클래스명 > 객체명(변수명)

	parents p1;
	ch1 c1;

	p1.pnum = 1;

	p1.pFunc();


	c1.ch1num = 2;
	c1.ch1Func();
	
	c1.pnum = 3;

	cout << "부모 클래스의 변수 p1.pnum= " << p1.pnum << endl;
	cout << "자식 클래스의 변수 c1.ch1num= " << c1.ch1num << endl;
	cout << "자식 클래스에서 부모 변수 c1.pnum= " << c1.pnum << endl;
}
728x90
728x90

생성자

- 객체가 생성될 때 자동으로 호출되는 함수

- 객체를 초기화시킬 수 있는 함수

- public 속성을 가진다

- 반드시 함수이름은 클래스명과 동일해야 한다

- 함수 오버로딩을 이용해서 정의할 수 있다. 

 

소멸자

- 어떤 클래스를 이용해서 생성한 객체가 메모리에서 해제될 때 자동으로 호출되는 함수

- 마무리 작업에서 유용

- public 속성을 가진다

- 반드시 함수이름은 클래스명과 동일해야 한다

- 함수 이름앞에 틸드 (~)기호를 붙여야 한다

 

 

생성자와 소멸자가 언제 나오는지 알 수 있는 코드:

#include <iostream>

using namespace std;

//생성자: 객체가 생성될 때 자동으로 호출되는 함수(객체 변수값 초기화시키기)
//소멸자: 객체의 사용이 끝나고 소멸될때 자동으로 호출되는 함수

class firstclass {

public:
	firstclass() {
		cout << "생성자가 호출되었습니다" << endl;

	}

	//소멸자는 클래스 이름과 똑같은 함수이름으로 설정하고 함수 앞에 ~ 붙임
	~firstclass() {
		cout << "소멸자가 호출되었습니다" << endl;

	}
};
int main() {

	firstclass A;

	cout << "main함수의 시작이다" << endl;
	cout << "main함수의 끝이다" << endl;


}

메인함수에서 동작하기 전에 생성자가 호출되고 메인함수가 처리 된 후 소멸자가 호출된 것을 볼 수 있다. 

 

 

#include <iostream>

using namespace std;

//생성자: 객체가 생성될 때 자동으로 호출되는 함수(객체 변수값 초기화시키기)
//소멸자: 객체의 사용이 끝나고 소멸될때 자동으로 호출되는 함수

class TV {
public:
	TV() {  //생성자 함수임
		poweron = true;
		channel = 20;
		volume = 20;
	}
	TV(bool po, int cha, int vol) {
		poweron = po;
		channel = cha;
		volume = vol;
	}

	bool poweron;
	int channel;
	int volume;
};

int main() {

	TV samsung;

	cout << "기본 전원 상태: " << samsung.poweron << endl;
	cout << "기본 채널 번호: " << samsung.channel << endl; 
	cout << "기본 볼륨 크기: " << samsung.volume << endl;
	cout << "----------------- " << endl;
	

	TV LG(true, 200, 20);

	cout << "기본 전원 상태: " << LG.poweron << endl;
	cout << "기본 채널 번호: " << LG.channel << endl;
	cout << "기본 볼륨 크기: " << LG.volume << endl;
	cout << "----------------- " << endl;



}

 

#include <iostream>

using namespace std;

class Time {

public:

	Time() {
		int hour = 11;
		int minute = 10;
		int second = 20;
	}

	Time(int h, int m, int s=0) {
		hour = h;
		minute = m;
		second = s;

	}
	int hour;
	int minute;
	int second;

};

int main() {
	Time t;
	Time t1(12, 20, 50);
	t.hour = 10;
	t.minute = 20;
	t.second = 30;

	cout << t.hour << "시" << t.minute << "분" << t.second << "초" << endl;
	cout << t1.hour << "시" << t1.minute << "분" << t1.second << "초" << endl;
}

멤버 변수가 클래스 바깥에 정의될 경우는 클래스 안에 함수 원형을 선언해서 사용

함수가 정의된 위치에서는 스코프연산자:: 사용

728x90

'언어는 과-학인가요? > C++' 카테고리의 다른 글

Protected, Private, Public 함수 : 이동시키기  (0) 2020.10.31
상속  (0) 2020.10.31
객체 지향 프로그래밍 (OOP)  (0) 2020.10.24
Namespace (이름공간)/ String  (0) 2020.10.10
C++ 입문  (0) 2020.10.10
728x90

OOP: Object Oriented Programing
Class: 구조체가 확장 된 것 

타입이 다른 변수 뿐만 아니라 함수까지 포함 ㄱㄴ

 

#include <iostream>

using namespace std;

class Car {
	bool poweron;
	string colour;
	int wheel;
	int speed;
	bool wiperon;
};
int main() {

	return 0;


}

 

함수 오버로딩(overloading)

 

중복가능: 다중정의

- 인수의 자료형이나 개수가 다름 동일한 이름의 함수를 여러개 정의하고 사용할수 있음

- 매개변수의 선언 형태를 이용하여 찾는다

- 매개변수의 자료형이나 개수가 달라야함

 

매개변수와 부분적 디폴트값 설정

- 반드시 오른쪽 매개변수의 디폴트값부터 채우는 형태로 정의해야함

- 함수에 전달되는 인수는 왼쪽에서부터 오른쪽으로 채워짐

 

 

요약

클래스

- 객체가 아니라 객체의 설계도이다

- 변수와 형은 같음

- 자체로는 값저장 ㅂㄱㄴ

특징 4가지

1. 캡슐화

- 클래스 안에 속하는 여러 변수나 함수를 하나의 클래스로 묶어줌

 

2. 은닉화

- 클래스 안에 속하는 변수나 함수는 원하는 부분만 외부에 공개하거나 비공개 할수 있음

(public, private)

 

3. 상속성

- 클래스간의 부모, 자식관계 형성 ㄱㄴ

- 자식 클래스는 부모 클래스의 멤버 강속가능. 근데 private은 ㅂㄱㄴ

 

4. 다형성

- 부모자식간에 형변환 성질

 

 

class접근 지정자

public

- 모든 맴버 접근, 멤버 변수 사용 ㄱㄴ

 

private

- 멤버 변수나 함수 외부 사용 ㅂㄱㄴ

- 클래스 맴버 함수 안에서는 사용 ㄱㄴ

 

protected 생성자 (Constructor)

- private와 같은 속성

- 상속관계일때 상위클래스의 멤버를 하위 클래스에서 private속성으로 사용 ㄱㄴ

 

Instance(인스턴스)

- 클래스로 실제 객체 만들기

- 메모리에 공간 만들기

- 변수 명 필요함

기본 형식 - 클래스명 변수명; //메모리에 객체가 만들어져 있는 주소가 담겨져있다

 

 

예제:

#include <iostream>

using namespace std;


class TV {

public: //어디서든 접근/사용가능한 함수
	bool poweron; //bool: 참거짓 나타냄 거짓=0 참=1
	int channel;
	int volume;

	void on() {
		poweron = true;
		cout << "TV 전원이 켜집니당" << endl;
	}
	void off() {
		poweron = false;
		cout << "전원꺼짐" << endl;
	}

	void setchannel(int ch)
	{
		if (ch >= 1 && ch <= 900)
		{
			channel = ch;
			cout << "채널이" << ch << "로 바뀌었습니다" << endl;
		}
	}

	void setvolume(int vol)
	{
		if (vol >= 0 && vol <= 30)
		{
			volume = vol;
			cout << "볼륨이" << vol << "로 바뀌었습니다" << endl;
		}
	}

};

int main() {
	TV samsung;//메모리에 삼성이라는 객체명으로 인스턴스화

	samsung.poweron = true;
	samsung.channel = 20;
	samsung.volume = 5;

	cout << "기본 전원 상태는: " << samsung.poweron << endl;
	cout << "기본 채녈 번호는: " << samsung.channel << endl;
	cout << "기본 볼륨 크기는: " << samsung.volume << endl;
	cout << "------------------------" << endl;

}

 

같은 변수나 함수를 계속 사용할수 있다

	TV LG;

	LG.poweron = false;
	LG.channel = 100;
	LG.volume = 30;

	cout << "기본 전원 상태는: " << LG.poweron << endl;
	cout << "기본 채녈 번호는: " << LG.channel << endl;
	cout << "기본 볼륨 크기는: " << LG.volume << endl;
	cout << "------------------------" << endl;

이렇게 lg도 추가가능

 

 

함수도 끌어다 쓸 수 있다. 

#include <iostream>

using namespace std;


class TV {

public: //어디서든 접근/사용가능한 함수
	bool poweron; //bool: 참거짓 나타냄 거짓=0 참=1
	int channel;
	int volume;

	void on() {
		poweron = true;
		cout << "TV 전원이 켜집니당" << endl;
	}
	void off() {
		poweron = false;
		cout << "전원꺼짐" << endl;
	}

	void setchannel(int ch)
	{
		if (ch >= 1 && ch <= 900)
		{
			channel = ch;
			cout << "채널이" << ch << "로 바뀌었습니다" << endl;
		}
	}

	void setvolume(int vol)
	{
		if (vol >= 0 && vol <= 30)
		{
			volume = vol;
			cout << "볼륨이" << vol << "로 바뀌었습니다" << endl;
		}
	}

};

int main() {

	TV samsung;//메모리에 삼성이라는 객체명으로 인스턴스화

	samsung.poweron = true;
	samsung.channel = 20;
	samsung.volume = 5;

	cout << "기본 전원 상태는: " << samsung.poweron << endl;
	cout << "기본 채녈 번호는: " << samsung.channel << endl;
	cout << "기본 볼륨 크기는: " << samsung.volume << endl;
	cout << "------------------------" << endl;

	TV LG;

	LG.poweron = false;
	LG.channel = 100;
	LG.volume = 30;

	cout << "기본 전원 상태는: " << LG.poweron << endl;
	cout << "기본 채녈 번호는: " << LG.channel << endl;
	cout << "기본 볼륨 크기는: " << LG.volume << endl;
	cout << "------------------------" << endl;

	LG.setchannel(150);
	LG.on();
	LG.setvolume(20);

}

 

728x90

'언어는 과-학인가요? > C++' 카테고리의 다른 글

Protected, Private, Public 함수 : 이동시키기  (0) 2020.10.31
상속  (0) 2020.10.31
생성자와 소멸자 (constructor and destructor)  (0) 2020.10.24
Namespace (이름공간)/ String  (0) 2020.10.10
C++ 입문  (0) 2020.10.10
728x90

이름공간(namespace)

- 이름을 붙여놓은 공간

- 특정 영역에 이름을 붙여주기 위한 문법적 요소

- 전역 함수나 변수의 유효범위에 이름을 붙여 분할시켜 중복(충돌)을 방지

 

#include <iostream>

namespace firstAdd {
	void add() {
		std::cout << "첫번째 공간이름 firstAdd 의 add함수를 출력" << std::endl;
	}
}

namespace secondAdd {
	void add() {
		std::cout << "두번째 공간이름 secondAdd 의 add함수를 출력" << std::endl;
	}
}

int main()
{
	firstAdd::add();
	secondAdd::add();
	
	return 0;
}

 

스코프 연산자 (::)

- 변수나 함수의 유효범위 = scope(스코프)

- 유효 범위 안에 같은 이름을 가진 변수나 함수가 있을땐 스코프 연산자를 사용한다

- 전역변수나 함수/오브젝트에 접근하는 우선순위 변경 가능

 

순서 바꿔서 출력도 ㄱㄴ

#include <iostream>

namespace firstAdd {
	void add();
}

namespace secondAdd {
	void add();
}

int main()
{
	firstAdd::add();
	secondAdd::add();

	return 0;
}


void firstAdd::add() {
	std::cout << "첫번째 공간이름 firstAdd 의 add함수를 출력" << std::endl;
}



void secondAdd::add() {
	std::cout << "두번째 공간이름 secondAdd 의 add함수를 출력" << std::endl;

}

 

이름공간의 중첩

 

#include <iostream>

namespace Parent {
	int number = 1;

	namespace SonOne {
		int number = 2;
	}

	namespace SonTwo {
		int number = 3;
	}
}

int main() {
	std::cout << Parent::number << std::endl;
	std::cout << Parent::SonOne::number << std::endl;
	std::cout << Parent::SonTwo::number << std::endl;

	return 0;

}

 

using으로 전역 이름공간으로 지정하기

#include <iostream>

using namespace std;

namespace firstAdd {
	void add();
}

namespace secondAdd {
	void add();
}

using namespace firstAdd;//전역으로 오픈시켜놈

int main()
{
	add();
	secondAdd::add();

	return 0;
}


void firstAdd::add() {
	std::cout << "첫번째 공간이름 firstAdd 의 add함수를 출력" << std::endl;
}



void secondAdd::add() {
	std::cout << "두번째 공간이름 secondAdd 의 add함수를 출력" << std::endl;

}

 

오브젝트에 접근하는 우선순위 변경

#include <iostream>

using namespace std;

int number = 100;

int main() {
	int number = 20;
	cout << number << endl;
	number += 20;
	::number += 50;
	cout << "지역변수 num출력 -> " << number << endl;
	cout << "지역변수 ::num출력 -> " << ::number << endl;

	return 0;

}

1. 지역변수 number출력

2. 지역변수에 20 더해서 출력

3. 스코프 연산자 붙여서 뽑으니까 전역변수에 50 더해져서 150나옴

 

== 스코프 연산자 붙으면 전역변수임

 

 

String

#include <iostream>

using namespace std;

int main() {
	char ch1 = 'A';
	char ch2[10] = "홍길동\0";

	cout << ch1 << endl;
	cout << ch2 << endl;

	string country = "Korea";
	string city = "Busan";

	cout << country << endl;
	cout << city << endl;

	string my_info = "I live in " + country + ", " + city;
	cout << "My information: " << my_info << endl;

	return 0;

}

728x90

'언어는 과-학인가요? > C++' 카테고리의 다른 글

Protected, Private, Public 함수 : 이동시키기  (0) 2020.10.31
상속  (0) 2020.10.31
생성자와 소멸자 (constructor and destructor)  (0) 2020.10.24
객체 지향 프로그래밍 (OOP)  (0) 2020.10.24
C++ 입문  (0) 2020.10.10

+ Recent posts