본문 바로가기

programming

C ++ 연습장

printf => std::cout(출력)<<"~~~~프린트 할꺼~~~~~"<<std::endl(개행문자);

 

scanf => std::cin>>"변수 이름"

std::cin, std::cout  둘다 변수 type 정의 필요 없음.

 

포인터 

주소 연산자  = > &

역참조 연산자 = > *

#include <iostream>

int main(void)

{

int x = 5;

std::cout<<x<<'\n';

std::cout<<&x<<'\n';

// X 의 주소

std::cout<<*&x<<'\n';

// X 의 주소를 가지고 역참조

}

// output

5
0x7ffc7eb1748c
5

 

 

매개변수의 디폴트 값

ex) int MyFunction(int num1, num2=1) { } 

이라고 하면 num2 에서 할당되지 않으면 default 로 1이 들어감

하지만 이때 오른쪽 부터 default 값이 저장 되어야함

 

지역 변수 전역 변수 

함수 내에서 사용되는 변수  => 지역변수

함수 내에서 전역 변수 사용하고 싶으면 "::전역변수"(전역 변수& 지역 변수 이름 겹쳤을때) 으로 사용가능

전역변수 & 지역변수 이름 다르면 그냥 바로 "전역변수" 로 사용가능

 

 

Call By Value & Call By Reference

Call By Value 는 값을 받아서 함수를 돌린다 => 따라서 함수 밖의 값에 영향을 미치지 않는다.

Call By Reference 는 값의 주소를 받아서 함수를 돌린다 => 따라서 함수 밖의 값에 영향을 미칠 수 있다.

Call By Value Call By Refernece (By Pointer) Call By Reference( By Refernece)

num1 = 10, num2 = 20

void
SwapByValue(int num1, int num2)

{

// Call by Value

int temp = num1;

num1 = num2;

num2 = temp;

std::cout<<num1<<std::endl;

std::cout<<num2<<std::endl;

}

num1, num2 값 안바뀜

num1 = 10, num2 = 20

void
SwapByRef(int *ptr1, int *ptr2)

{

// Call by Reference

int temp = *ptr1;

*ptr1 = *ptr2;

*ptr2 = temp;

}

num1, num2 값 바뀜

num1 = 10, num2 = 20

void
 SwapByRef(int &ptr1, int &ptr2)

{

// Call by Reference

int temp = ptr1;

ptr1 = ptr2;

ptr2 = temp;

}

num1, num2 값 바뀜

 

 

Reference(참조자)

int x = 5;

int &ref = x;

일때 ref 도 x 와 마찬가지로 5가 된다. 이때 ref 를 바꾸면 x 도 같이 바뀌게 된다.

 

참조자가 변수를 못 바꾸도록 한다면.

const int & ref  => 이런식으로 적으면 ref로 인한 다른 변수 바뀜이 없다.

 

 

기본 입출력 예시

#include <iostream> // 전처리기
#include <fstream> // 입출력 스트림 (파일 불러 읽고 쓰기)
using namespace std;

int main(void)
{
	int no1;
	cin >> no1; // 입력 연산자
	cout << "입력된 정수 : " << no1 << endl;  // 입력된 정수 : no1(값) 으로 표시

	cout << "1" << "2" << "3";
	cout << "4"; // endl 이 있어야지 띄워쓰기 가능 1234 로 프린트 된다.

	
	return 0;
}

파일 입출력 예시

#include <iostream> // 전처리기
#include <fstream> // 입출력 스트림 (파일 불러 읽고 쓰기)
using namespace std;

int main(void)
{
	int kor, eng, mat, total;
	double aver;
	ifstream fin("sungjuk.txt"); // 입력 스트림
	ofstream fout("sungjuk-report.txt"); // 출력 스트림

	fin >> kor >> eng >> mat;
	while (fin) {
		total = kor + eng + mat;
		aver = (double)total/3;
		fout << total << " " << aver << endl;
		fin >> kor >> eng >> mat;
	}
	fin.close();
	fout.close(); // 열었던 파일 닫기 
	return 0;
}

스트링 합치기

#include <iostream> // 전처리기
#include <string>
using namespace std;

int main(void)
{
	string name;
	string st = " -> 성명 :";

	cout << "* 이름을 입력하시오: ";
	cin >> name;
	name = st + name;
	cout << name << endl;
	return 0;
}

함수 예시

#include <iostream> // 전처리기
using namespace std;

int addition(int, int); // 함수 원형
int addition_2(int*, int*); // call by address  포인터 변수 사용
int addition_3(int&, int&); // call by reference 참조자 사용

int main(void)
{
	int a, b, hap;

	cout << "2개의 정수 : ";
	cin >> a >> b; // 하나쓰고 엔터나 띄어쓰기 있으면 인식 가능함
	hap = addition(a, b); // 그냥 부르면 된다.
	hap = addition_2(&a, &b); // 주소 값으로 불러야 한다.
	hap = addition_3(a, b); // 참조자 연산이므로 그냥 쓴다.
	cout << " 합계 : " << hap;
	return 0;
}

int addition(int x, int y)
{
	int z;
	z = x + y;
	return z;
}

int addition_2(int* x, int* y) 
{
	int z;
	z = *x + *y; // 포인터 변수라서 주소 값을 역 참조 해야한다.
	return z;
}

int addition_3(int& x, int& y)
{
	int z;
	z = x + y;
	return z;
}

배열 

int no[10];
no == &no[0], *no == no[0] 이다.

구조체 사용 예시

#include <iostream> // 전처리기
#include <cstring>
using namespace std;

struct student {
	int id_no;
	char name[20];
	int dept_code;
};

int main(void)
{
	student st1 = { 20,"kevin",10 },st2;
	st2 = st1;
	st2.id_no = 1000;
	student* pt = &st1; // 포인터 변수로 선언
	cout << pt -> id_no << pt -> name; // 간접참조 연산자(->) 사용하는법
	cout << st1.id_no << st1.name << endl;
	cout << st2.id_no << st2.name << endl;
	strcpy_s(st2.name, "홍길동"); // 바꿔 주는 함수
	cout << st2.id_no << st2.name << endl;
	return 0;
}

클래스 사용 예시 1

#include <iostream> // 전처리기
using namespace std;

class Rectangle {
public: // 접근 권한 지정
	int width;
	int height;
	int get_Area(); // 클래스 내부에서는 선언만 가능, 초기화 불가능
};

int Rectangle::get_Area() // 범위 지정 연산자 (::) 을 사용해서 접근
{
	return width * height; // public 으로 정의되어 있기 때문에 접근 가능
}

int main(void)
{
	Rectangle rect;
	rect.width = 3; // 클래스내의 변수는 변수 연산자 dot(.) 을 사용해서 접근
	rect.height = 5; // 클래스 내의 포인터는 포인터 연산자 (->) 을 사용해서 접근
	cout << "사각형의 면적은";
	cout << rect.get_Area() << endl;
	return 0;
}

클래스 사용 예시 2

#include <iostream> // 전처리기
using namespace std;

class Rectangle {
	int width;
	int height;
public: // 접근 권한 지정
	void set_width(int w) {
		width = w;
		return;
	}
	void set_height(int);
	int get_Area(); // 클래스 내부에서는 선언만 가능, 초기화 불가능
};

void Rectangle::set_height(int h) {
	height = h;
	return;
}

int Rectangle::get_Area() // 범위 지정 연산자 (::) 을 사용해서 접근
{
	return width * height; // public 으로 정의되어 있기 때문에 접근 가능
}

int main(void)
{
	Rectangle rect;
	rect.set_width(3); 
	rect.set_height(5); 
	cout << "사각형의 면적은";
	cout << rect.get_Area() << endl;
	return 0;
}

클래스 header 파일에 작성 예시

클래스의 선언은 header 파일에 작성하는게 일반적이다.

Rectangle.h Rectangle.cpp
#ifndef Rectangle_h
#define Rectangle_h
class Rectangle {
int width;
int height;
public:
void set_width(int);
void set_height(int);
int get_Area();
};
#endif
#include <iostream> // 전처리기
#include "Rectangle.h" //미리 선언한 헤더 파일
using namespace std;

void Rectangle::set_width(int w)
{
width = w;
return;
}
void Rectangle::set_height(int h) {
height = h;
return;
}

int Rectangle::get_Area() // 범위 지정 연산자 (::) 을 사용해서 접근
{
return width * height; // public 으로 정의되어 있기 때문에 접근 가능
}

int main(void)
{
Rectangle rect;
rect.set_width(3); 
rect.set_height(5); 
cout << "사각형의 면적은";
cout << rect.get_Area() << endl;
return 0;
}

생성자는 클래스가 시작할때 초기 선언을 해주는 것이다. 생성자는 중복이 가능하다.

생성자 예시

#include <iostream> // 전처리기
#include <string>
using namespace std;

class Animal {
public:
	Animal(); // 생성자 
	Animal(int, int, string); // 생성자 매개변수 => 초반에 정의 해줘야한다.
	string getName()
	{
		return name;
	}
private:
	int sp_code;
	int origin_code;
	string name;
};

Animal::Animal()
{
	sp_code = 0;
	origin_code = 10;
	name = "발발이";
}

Animal::Animal(int s, int o, string n) // 매개변수의 수에 따라 생성자 이름은 중복 가능하다
{
	sp_code = s;
	origin_code = o;
	name = n;
}

int main(void)
{
	Animal a; // 매개변수 없는 생성자로 실행
	Animal b(1, 5, "멍멍이"), c(2, 10, "살살이"); // 매개변수 생성자로
	cout << a.getName() << endl;
	cout << b.getName() << endl;
	cout << c.getName() << endl;
	return 0;
}

아래 둘은 동치 이다. 

class Animal {
public:
Animal(); // 생성자 
Animal(int, int, string); // 생성자 매개변수 => 초반에 정의 해줘야한다.
string getName()
{
return name;
}
private:
int sp_code;
int origin_code;
string name;
};

Animal::Animal()
{
sp_code = 0;
origin_code = 10;
name = "발발이";
}

Animal::Animal(int s, int o, string n) // 매개변수의 수에 따라 생성자 이름은 중복 가능하다
{
sp_code = s;
origin_code = o;
name = n;
}
class Animal {
public:
Animal() {int s= 0, int o = 10, string n = "발발이"}; // 생성자 
Animal(int, int, string) : sp_code(s), origin_code(o), name(n) {}; // 생성자 매개변수 => 초반에 정의 해줘야한다.
string getName()
{
return name;
}
private:
int sp_code;
int origin_code;
string name;
};

소멸자는 ~ 로 시작을 하며 1개만 존재 한다. 주로 동적할당 메모리의 반환, 파일 닫기 등이 있다.

소멸자 예시

class Animal {
public:
	Animal() {int s= 0, int o = 10, string n = "발발이"}; // 생성자 
	Animal(int, int, string) : sp_code(s), origin_code(o), name(n) {}; // 생성자 매개변수 => 초반에 정의 해줘야한다.
	~Animal();
	string getName()
	{
		return name;
	}
private:
	int sp_code;
	int origin_code;
	string name;
};

Animal::~Animal()
{

}

동적 메모리 관리

#include <iostream> // 전처리기
using namespace std;

int main(void)
{
	int n;
	cout << "정수의 수는 : ";
	cin >> n;
	int* data = new int[n]; // 동적 할당
	cout << n << "개 정수 입력 :";
	for (int i = 0; i < n; i++)
		cin >> data[i];
	cout << " < 입력 정수 <\n";
	for (int i = 0; i < n; i++) {
		cout << hex << data + i;
		cout << "번지: ";
		cout << dec << data[i];
		cout << endl;
	}
	delete[] data; // 메모리 반환
	return 0;
}

const => 상수 만들기 & 멤버 변수를 건들지 않겠다.

#include <iostream> // 전처리기
#include <string>
using namespace std;

class Car {
	const string model; // 상수 멤버 변수 => 값을 더이상 변경하지 않겠다.
	bool power;
	double speed;
public:
	Car(string m, bool p = false, double s = 0.0) :model(m), power(p), speed(s) {};
	void set_power();
	void set_speed(bool);
	double get_speed() const; // 상수 멤버 함수 => 멤버 변수를 아무것도 건드리지 않겠다.
};
void Car::set_power()
{
	power = !power;
	return;
}
void Car::set_speed(bool a)
{
	if (!power)return;
	if (a)
		speed += 0.1;
	else
		speed -= 0.1;
	return;
}
double Car::get_speed() const
{
	return speed;
}

int main(void)
{
	Car car1("소나타");
	car1.set_power();
	car1.set_speed(true);
	cout << car1.get_speed() << endl;
	return 0;
}

static = 정적 멤버 선언

C++에서 정적 멤버란 클래스에는 속하지만, 객체 별로 할당되지 않고 클래스의 모든 객체가 공유하는 멤버를 의미합니다.

멤버 변수가 정적(static)으로 선언되면, 해당 클래스의 모든 객체에 대해 하나의 데이터만이 유지 관리됩니다.

정적 변수 예시

아래와 같이 정적 멤버를 사용한다면 클래스가 생성될때 마다 person_count 는 증가한다.

class Person

{

private:

    string name_;

    int age_;

public:

    static int person_count_;            // 정적 멤버 변수의 선언

    Person(const string& name, int age); // 생성자

    ~Person() { person_count_--; }       // 소멸자

    void ShowPersonInfo();

};  

...

int Person::person_count_ = 0; // 정적 멤버 변수의 정의 및 초기화

클래스의 상속 => 기존의 멤버(부모, 슈퍼, 베이스)를 물려 받고, 필요한 멤버를 추가하여 새로운 클래스(자식, 서브, 파생)를 정의함

단 부모 클래스의  private member 는 접근 불가

상속 예시

class 자식_class : public 부모_class

#include <iostream> // 전처리기
#include <string>
using namespace std;

class Animal {
protected:
	int sp_code;
	int origin_cd;
	string name;
public:
	Animal() {};
	string get_name() {
		return name;
	};
	void Cry() {
		cout << "울음" << endl;
		return;
	};
};

class Dog : public Animal { // 부모 클래스의 상속
	int color;
public:
	Dog(int, int, string, int);
	void Run() {};
};

Dog::Dog(int s, int o, string n, int c) {
	sp_code = s;
	origin_cd = o;
	name = n;
	color = c;
}

int main(void)
{
	Dog a(10, 20, "발발이", 5);
	a.Cry();
	cout << a.get_name() << endl;
	return 0;
}

상속에서는 부모 클래스의 생성자가 먼저 실행되고 자식 클래스의 생성자가 이후에 실행된다.

상속 클래스 생성자 예시

#include <iostream> // 전처리기
#include <string>
using namespace std;

class Animal {
protected:
	int sp_code;
	int origin_cd;
	string name;
public:
	Animal(int, int o, string n) :sp_code(s), origin_cd(o), name(n) {};
	string get_name() {
		return name;
	};
	void Cry() {
		cout << "울음" << endl;
		return;
	};
};

class Dog : public Animal { // 부모 클래스의 상속
	int color;
public:
	Dog(int, int, string, int);
	void Run() {};
};

Dog::Dog(int s, int o, string n, int c):
Animal(s,o,n){ // 부모 클래스의 생성자 실행
	color = c; // 자식 클래스의 생성자 실행
}

int main(void)
{
	Dog a(10, 20, "발발이", 5);
	a.Cry();
	cout << a.get_name() << endl;
	return 0;
}

'programming' 카테고리의 다른 글

아두이노 센서 사용 코드 예시  (0) 2020.05.07
git hub 사용법 Manual  (0) 2020.02.16
ROS 연습장 (python, C++)  (0) 2020.02.03
파이썬 코딩 연습장  (0) 2020.01.10