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
728x90

레몬타르트

- 블랙업커피

- 고메

 

레몬파운드

- 라로커피 (raro)

 

 

728x90

+ Recent posts