산술연산자뿐 아니라 입출력연산자도 오버로딩이 가능하다.

입출력연산자 오버로딩을 하지않고 print함수로 구현하면 코드의 양이 많아질 수 있다.

int main()
{
	Point p1(3.2, 3.1, 3.5);
	cout << "p1 : " << &p1 << endl;
	Point p2(1.2, 1.1, 1.5);
	cout << "p2 : " << &p2 << endl;

	//print함수사용
	p1.Print();
	cout << " ";
	p2.Print();
	cout << endl;
    return 0;
}


ostream,istream으로 입출력을 정의할 수 있다.
ostream,istream모두 파일입출력에 사용할 수 있어 파일입출력도 같이 사용할 수 있다.

	friend std::ostream& operator << (std::ostream &out, const Point &point) {
		out << point.m_x+1.0 << " " << point.m_y+1.0 << " " << point.m_z + 1.0;
		return out;
	}
	//const아님
	friend std::istream& operator >> (std::istream &in, Point &point) {
		in >> point.m_x >> point.m_y >> point.m_z;
		return in;
	}


파일입출력은 fstream를 include해야한다.

#include <fstream>

입출력 오버로딩 및 기본파일 입출력 코드

#include <iostream>
#include <fstream>

using namespace std;

class Point
{
private:
	double m_x, m_y, m_z;

public:
	Point(double x, double y, double z)
		:m_x(x), m_y(y), m_z(z) {

	}
	double getX() {
		return m_x;
	}
	double getY() {
		return m_y;
	}
	double getZ() {
		return m_z;
	}

	void Print() {
		cout << m_x << " " << m_y << " " << m_z;
	}

	friend std::ostream& operator << (std::ostream &out, const Point &point) {
		out << point.m_x+1.0 << " " << point.m_y+1.0 << " " << point.m_z + 1.0;
		return out;
	}
	//const아님
	friend std::istream& operator >> (std::istream &in, Point &point) {
		in >> point.m_x >> point.m_y >> point.m_z;
		return in;
	}
};

int main()
{
	Point p1(3.2, 3.1, 3.5);
	cout << "p1 : " << &p1 << endl;
	Point p2(1.2, 1.1, 1.5);
	cout << "p2 : " << &p2 << endl;

	//print함수사용
	p1.Print();
	cout << " ";
	p2.Print();
	cout << endl;

	cout << p1 << " " << p2 << endl;
	//파일출력
	ofstream of("out.txt");
	of << p1 << " " << p2 << endl;
	of.close();


	//파일입력
	ifstream is("out.txt");
	is >> p1 >> p2;
	is.close();

	cout << p1 << " " << p2 << endl;
	return 0;
}

int,double등 기본자료형은 산술연산자가 정의되어있다.

사용자정의자료형 ex)class 끼리도 산술연산자를 만들어 줄 수 있다.

 

operator를 사용해서 만들 수 있다.


밖에서 함수로 생성할 수 있다
-외부 함수이므로 public함수로 값을 가져와 더해주어야한다.

//외부함수
Cents operator +(const Cents &c1, const Cents &c2) {
	return Cents(c1.getCents() + c2.getCents());
}



밖의 함수를 friend로 선언할 수 있다.
-friend 선언으로 private 자료형에 접근가능하다.

...
public:
	//class 내부 friend 선언
	friend Cents operator +(const Cents &c1, const Cents &c2);
 ...
 //클래스외부
 //friend선언
Cents operator +(const Cents &c1, const Cents &c2) {
	//private 변수 접근가능
	return Cents(c1.m_cents + c2.m_cents);
}


클래스 내부함수로 this를 사용할 수 있다.
-생성된 함수에서 시작하므로 this로 현재값과 파라미터 값을 더해준다.

//class 내부함수 this사용
public:
	Cents operator +(const Cents &c2) {
		cout << this << endl;
		cout << "this->m_cents : " << this->m_cents << endl;
		cout << "c2.m_cents : " << c2.m_cents << endl;

		return Cents(this->m_cents + c2.m_cents);
	}

내부함수는 첫번째 인자의 주소에서 시작한다.

계속 더해가는 구조라고 생각하면된다.

첫번째 인자 접근 -> 첫번째 인자값(this로 접근) + 두번째 인자값 ->새로운 주소 할당

 

#include <iostream>

using namespace std;

class Cents
{
private:
	int m_cents;

public:
	Cents(int cent): m_cents(cent){}
	int getCents() const { return m_cents; }
	//friend Cents operator +(const Cents &c1, const Cents &c2);
	Cents operator +(const Cents &c2) {
		cout << this << endl;
		cout << "this->m_cents : " << this->m_cents << endl;
		cout << "c2.m_cents : " << c2.m_cents << endl;

		return Cents(this->m_cents + c2.m_cents);
	}
};

////friend선언
//Cents operator +(const Cents &c1, const Cents &c2) {
//	return Cents(c1.m_cents + c2.m_cents);
//}
//
////외부함수
//Cents operator +(const Cents &c1, const Cents &c2) {
//	return Cents(c1.getCents() + c2.getCents());
//}

int main()
{
	Cents c1(4);
	cout << "c1 : " << &c1 << endl;
	Cents c2(5);
	cout << "c2 : " << &c2 << endl;

	cout << (c1 + c2 + Cents(10)+Cents(11)).getCents() << endl;

	return 0;

}

실행시간측정하기

프로그램 생성시 실행시간을 알고싶을 수 있다.
chrono를 사용한 Timer Class를 생성해서 사용하자.

출력되는 시간을 완벽히 믿진말자. 때마다 달라질 수 있다.

#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
#include <chrono>

using namespace std;

class Timer
{
	using clock_t = std::chrono::high_resolution_clock;
	using second_t = std::chrono::duration<double, std::ratio<1>>;

	std::chrono::time_point<clock_t> start_time = clock_t::now();

public:
	void elapsed()
	{
		std::chrono::time_point<clock_t> end_time = clock_t::now();

		cout << std::chrono::duration_cast<second_t>(end_time - start_time).count() << endl;
	}

};

int main()
{
	Timer t;
	vector<int> vec(1000);
	for (int i = 0; i < vec.size(); i++) {
		vec[i] = i;
	}
	for (int i = 0; i < vec.size(); i++) {
		cout << vec[i] << endl;
	}
	t.elapsed();
	return 0;
}

익명객체 anonymous

이름이 붙은 변수(R-value)를 사용하지않고 바로사용한다.

한번만 사용할 멤버함수를 class를 인스턴스생성하고 사용하면 비효율적이다.

Class를 R-value처럼 접근해 사용가능하다.
재사용은 불가능하다.

계속 새로 생성한다고 생각하면된다. 생성자,소멸자로 확인 가능하다.

 

#include <iostream>

using namespace std;
class A
{
private:
	int a;
public:
	void print()
	{
		cout << "Hello" << endl;
	}
	A(const int& val)
		:a(val){
		cout << val << endl;
		cout <<this<< " constructor" << endl;
	}
	~A()
	{
		cout << this <<" destructor" << endl;
	}
	int getA() const {
		return a;
	}
};

A add(const A& a1, const A& a2) {
	return A(a1.getA() + a2.getA());
}

int main()
{
	A a(1);
	//아래 두 인스턴스는 주소가 다르다.
	A(1).print();
	A(2).print();
	
	cout << add(A(3), A(4)).getA() << endl;

	return 0;
}

친구 함수와 클래스
여러개의 클래스 복잡하게 상호작용하면 클래스간의 상호작용을 깔끔히 정리하기 어렵다.
이때 친구함수와 친구클래스를 사용한다.

클래스안에 함수를 friend로 선언한다.

A,B 두 class가 있다고 생각해보자.
A class에 B class를 friend로 선언하게되면
B class에서 A class private:(캡슐화)에 관여가 가능하게된다.

friend선언은 class를 통째로도 가능하고 일부함수만 따로도 가능하다.

friend함수 선언할때 함수의 생성되는 위치를 잘보고 구현해야한다.

 

#include <iostream>

using namespace std;
//전방선언
class A;

class B
{
private:
	int m_val = 2;

public:
	//A가 선언되어 있기에 A를 사용가능하다.
	void doSomething(A& a);
};

class A
{
private:
	int m_val = 1;
	//class A가 생성될떄 B를 알 수없다.
	//class통쨰로 선언
	//friend class B;
	//B Class가 먼저 선언되어 있어 함수를 구현할 수 있다.
	//class일부함수만 선언
	friend void B::doSomething(A& a);
};

//A에 m_val변수가 있는지 확인 불가능하기때문에 A Class가 구현된후 함수 구현
void B::doSomething(A& a) {
	a.m_val = 3;
	cout << a.m_val << endl;
}

int main()
{
	A a;
	B b;
	b.doSomething(a);
	

	return 0;
}

정적멤버변수 (static)

정적변수는 한번선언되면 초기화하지않고 계속 증가한다.

정적멤버변수도 마찬가지로 한 메모리 주소를 보고 있기에
인스턴스를 몇번이고 생성해도 같은 변수주소를 보고 있다.

static만 선언하면 변수를 클래스 밖에서 초기화해주어야하고
static const로 선언하면 클래스안에서 초기화가 가능하다. 

 

#include <iostream>

using namespace std;

int generateID() {
	static int s_id = 0;
	cout << &s_id << endl;
	return ++s_id;
}

class Something
{
public:
	static int s_value;
};

int Something::s_value = 1;

int main()
{
	//계속 늘어나는걸 볼 수 있다.
	cout << generateID() << endl;
	cout << generateID() << endl; 
	cout << generateID() << endl;

	Something st1;
	Something st2;

	st1.s_value = 2;

	cout << &st1.s_value << " " << st1.s_value << endl;
	cout << &st2.s_value << " " << st2.s_value << endl;
	return 0;
}

정적멤버함수

정적멤버함수와 정적멤버변수와 비슷한듯 다르다.

정적멤버변수,함수는 인스턴스로 정의되기전 클래스 접근 또는
모든 인스턴스에서 접근이가능하다. (메모리공유)

정적멤버함수는 this를 사용하지 못한다.
정적멤버함수는 정적멤버변수만 리턴할 수 있다.

#include <iostream>

using namespace std;

class Something
{
private:
	static int m_value;
	int p_value = 1024;
public:
	Something() {
	}
	
	static int getValue() {
		return m_value+1;
	}

	int getPValue() {
		return this -> p_value + this ->m_value;
	}

};

int Something::m_value = 1024;

int main()
{
	cout << Something::getValue << endl;
	cout << Something::getValue() << endl;

	Something st;
	cout << st.getValue() << endl;

	//멤버함수
	int(Something::*ptr)() = &Something::getPValue;
	//정적멤버함수
	int (*ptr2)() = Something::getValue;

	cout << "=============" << endl;
	cout << (st.*ptr)() << endl;
	cout << (*ptr2)() << endl;

	return 0;
}

클래스와 const

const는 변수를 상수로 만들고 싶을때 사용한다.

클래스의 인스턴스(변수,오브젝트)를 생성할때 const를 선언하면 

인스턴스(변수,오브젝트)는 상수이기때문에 내부의 값을 변경할 수 없다.


보통 멤버함수로는 내부의 값을 변경하지 않더라도 값을 가져오는 함수도 사용할 수 없다.

	const Something something;
	//상수이기 떄문에 에러가 난다.
	//something.setValue(1);


사용할려면 컴파일러가 판단할때는 멤버함수 뒤에 const를 선언해줘야한다.
멤버함수에 const를 선언하면 컴파일러에게 완벽히 const라고 확인해주는 것이다.

	//const를 선언해주어야한다.
	int getValue() const {
		return m_value;
	}



인스턴스를 파라미터로 복사하게되면 클래스 내부에 숨어져있는 복사 컨스트럭터가 인스턴스를 복사해준다.

	//복사 컨스트럭터
	Something(const Something& st_in) {
		m_value = st_in.m_value;
	}


인스턴스(오브젝트,객체) 파라미터도 const 클래스명&를 해주면 복사하지 않는다.

또 const로 파라미터구분없이 오버로딩을 할 수 있다.

	string& getStrValue() {
		return m_StrValue;
	}

	const string& getStrValue() const{
		return m_StrValue;
	}

 

코드정리

#include <iostream>
#include <string>

using namespace std;

class Something
{
public:
	int m_value = 0;
	string m_StrValue = "default";

	//복사 컨스트럭터
	Something(const Something& st_in) {
		cout << "copy Constructor" << endl;
		m_value = st_in.m_value;
	}
	Something() {
		cout << "Constructor" << endl;
	}

	void setValue(int value) {
		m_value = value;
	}
	//const를 선언해주어야한다.
	int getValue() const {
		return m_value;
	}
	
	string& getStrValue() {
		return m_StrValue;
	}

	const string& getStrValue() const{
		return m_StrValue;
	}

};

void print(Something st) {
	cout << &st << endl;
	cout << st.getValue() << endl;
}

void print2(const Something& st) {
	cout << &st << endl;
	cout << st.getValue() << endl;
}

int main()
{
	const Something something;
	//상수이기 떄문에 에러가 난다.
	//something.setValue(1);
	//클래스안 멤버함수에 const를 선언해주어야한다.
	something.getValue();

	cout << "=====================================" << endl;
	//복사 컨스트럭터 작동
	Something something2;
	cout << &something2 << endl;
	print(something2);

	cout << "=====================================" << endl;
	//const 파라미터
	cout << &something2 << endl;
	print2(something2);

	cout << "=====================================" << endl;

	//string 테스트
	something2.getStrValue() = "Test";
	cout << something2.getStrValue() << endl;

	const Something something3;
	//변경불가
	//something3.getStrValue() = "TEST";
	cout << something3.getStrValue() << endl;
	return 0;
}

소멸자 Destructor

변수가 영역을 벗어나 사라질때 호출이되는 함수

소멸자를 선언할땐 ~클래스명()으로 선언한다.

//IntArr클래스의 소멸자 생성
public:
	//소멸자 Destructor
	//지역을 벗어날때 자동으로 실행된다.
	~IntArr() {
		if (m_arr != nullptr) {
			delete[] m_arr;
		}


동적할당을 받을때 자주 사용한다.
반복문에서 동적할당을 할때 delete를 소멸자로 선언해 놓으면 자동으로 메모리를 반납한다.

#include <iostream>

using namespace std;

class Simple
{
private:
	int m_id;
public:
	Simple(const int& id)
		:m_id(id) {
		cout << "Constructor" << m_id << endl;
	}

	~Simple() {
		cout << "Destructor" << m_id << endl;
	}
};

class IntArr
{
private:
	int *m_arr = nullptr;
	int m_length = 0;

public:
	IntArr(const int length_in) {
		m_length = length_in;
		m_arr = new int(length_in);
	}
	//소멸자 Destructor
	//지역을 벗어날때 자동으로 실행된다.
	~IntArr() {
		if (m_arr != nullptr) {
			delete[] m_arr;
		}
	}

	int size() {
		return m_length;
	}
};
int main()
{
	//{}지역을 벗어날때 자동으로 소멸자가 자동으로 실행
	Simple *s1 = new Simple(0);
	Simple s2(1);
	Simple s3(2);
	delete s1;

	return 0;
}

this포인터

클래스를 붕어빵찍는 틀을 비유한다.
생성된 붕어빵은 인스턴스이다.

각인스턴스들을 구분하는 방법

this포인터는 클래스안에 숨어있다.
숨어있는 this로 자기 자신의 주소를 알 수 있다.

 

클래스안에 함수들에 this가 선언되어있지만 안보이는것이다.

	void setId(int id) {
    	//this -> m_id = id;
		m_id = id;
	}


클래스안에 함수들은 클래스가 선언될때마다 만들지 않는다.
함수가 하나만 선언되고 메모리주소와 설정한 인자값을 넣어주는 구조이다.


연쇄호출 Chaining Member Functions
체이닝함수

this포인터를 이용해 자기자신을 다시 호출한다.
체이닝함수는 한번에 여러번 선언할 수 있다.

#include <iostream>

using namespace std;

class Simple
{
private:
	int m_id;
public:
	Simple(const int &id)
		:m_id(id) {
		cout <<"this : "<< this << endl;
		//->포인터에 값을 넣는것
		this->m_id;
	}
	void setId(int id) {
    	//아래 this->가 생략되어 보이는것이다.
        //this->m_id =3;
		m_id = id;
	}
	int getId() {
		return m_id;
	}
	//체이닝 함수
	Simple& nextId() {
		m_id += 1;
		return *this;
	}
	void print() {
		cout << "nextId : " << m_id << endl;
	}
};
int main()
{
	Simple s1(1), s2(2);
	s1.setId(3);
	s2.setId(4);
	s2.print();
	/*
	체이닝함수 동작의 이해
	Simple& sim = s2.nextId();
	sim = s2.nextId();
	sim = s2.nextId();*/
	s2.nextId().nextId().nextId().print();

	cout << "&s1 : " << &s1 << " &s2 : " << &s2 << endl;
	return 0;
}

 

생성자의 멤버들을 초기화
Member initializer list

생성자 선언할때 :를 이용해 선언한다.

public:
	Something()	//우선순위가 가장 높다.
		: m_i(1), m_d(3.14), m_c('a') ,m_b(m_i-1)
	{
	}


생성자 선언이 멤버선언시 기본값선언, 생성자에 변수에 값대입 보다 가장 우선순위가 높다.

#include <iostream>

using namespace std;
class B
{
private:
	int m_b;
public:
	B(const int& m_b_in)
		: m_b(m_b_in) {

	}
};
class Something
{
private://생성자 초기화가 있을시 기본값설정은 무시된다.
	int m_i = 100;
	double m_d = 200.1;
	char m_c = 'b';
	B m_b{ 2 };

public:
	Something()	//우선순위가 가장 높다.
		: m_i(1), m_d(3.14), m_c('a') ,m_b(m_i-1)
	{//생성자 초기화 선언후 동작한다.
		m_i *= 3;
		m_d *= 3;
	}
	void print() {
		cout << m_i << " " << m_d << endl;
	}
};

int main() {
	Something s;
	s.print();

	return 0;
}

위임생성자
Delegathing Constructors
생성자가 다른생성자를 사용하는것을 말한다.
파라미터가 여러개일때 자주 사용한다.

객체지향은 초기화,인풋은 하나인게 좋다.

과거엔 초기화함수(ex:init)를사용했으나 최근 c++에선 위임생성자를 지원해준다.

 

#include <iostream>
#include <string>

using namespace std;

class Student
{
private:
	int		m_id;
	string	m_name;

public:

	Student(const string& name)
		: Student(0,name) //위임생성자
	{

	}
	Student(const int& id, const string& name)
		:	m_id(id),
			m_name(name) 
	{
		//과거엔 초기화함수를 사용했다.
		init(id, name);
	}

	//초기화함수
	void init(const int& id, const string& name) {
		m_id = id;
		m_name = name;
	}

	void print() {
		cout << "id : " << m_id << " name : " << m_name << endl;
	}
	
};
int main()
{
	Student st1(0, "Choi");
	st1.print();

	//위임생성자
	Student st2("Choi");
	st2.print();
	return 0;
}

생성자 Constructor
객체를 설계하면 객체가 생성될때 객체가 생성되자마자 기능(값설정)을 수행해야하는 때가있다.
이때 생성자를 사용한다.

private으로 캡슐화된 클래스 변수의 기본값을 정의한다.
변수에 기본값을 선언해줄 수 있지만 기본값이 매번 달라질 수 있다.

반환 리턴타입이 없고 클래스와 이름이 같으면 생성자이다.

public:
	//기본생성자
	Fraction()
	{
		m_numerator = 0;
		m_denominator = 1;
	}
    


자동실행
생성자를 선언해놓으면 클래스가 메모리가 올라가 인스턴스가 될때 생성자를 실행한다.

생성자도 함수인데 파라미터가 없다면 ()를 하면안된다.
파라미터에 default value도 선언가능하다.
모든 파라미터에 default value를 선언하면 기본생성자를 생성하지 못한다.



개발자가 생성자를 선언안하면 클래스안에 default생성자(기본)가 숨어있다.

 

클래스안에 다른 멤버클래스가 선언되어있으면 멤버클래스가 먼저 생성된다.

class Second
{
public:
	Second() {
		cout << "Second" << endl;
	}
};

class First
{
	//멤버클래스가 먼저생성된다.
	Second sec;

public:
	First() {
		cout << "First" << endl;
	}
};


생성자를 선언하면 {}초기화가 가능해진다. {}은 형변환이 지원되지 않는다.

#include <iostream>

using namespace std;

class Second
{
public:
	Second() {
		cout << "Second" << endl;
	}
};

class First
{
	//멤버클래스가 먼저생성된다.
	Second sec;

public:
	First() {
		cout << "First" << endl;
	}
};
class Fraction
{
private:
	//분자
	int m_numerator;
	//분모
	int m_denominator;

public:
	//기본생성자
	Fraction()
	{
		m_numerator = 0;
		m_denominator = 1;
	}
	Fraction(const int& n, const int& d)
	{
		m_numerator = n;
		m_denominator = d;
	}
	void print()
	{
		cout << m_numerator << " / " << m_denominator << endl;
	}

};

int main()
{
	Fraction frac(1.0,3);
	frac.print();
	//기본생성자는 ()가 없다.
	Fraction frac2;
	frac2.print();

	//frac와 다르게 1.0으로 초기화되지않는다.
	Fraction frac3 = Fraction{ 1,2 };
	frac3.print();

	//class안에 class생성순서확인
	First f;
	return 0;
}

+ Recent posts