다형성의 기본개념

자식클래스의 객체에 부모 클래스의 포인터를 사용한다면?

 

부모클래스 *포인터 = 자식클래스;


위처럼 하면 부모클래스의 메소드가 실행된다. 

하지만 virtual을 메소드에 붙여주면 자식 메소드가 실행되게 된다.

	virtual void speak() const
	{
		cout << m_name << " ??? " << endl; 
	}


자식클래스에 메소드가 없으면 부모클래스가 실행된다.

이걸 다형성이라고 부른다.

 

#include <iostream>
#include <string>

using namespace std;

class Animal
{
protected:
	string m_name;

public:
	Animal(string name)
		: m_name(name) {

	}

	string getName() { return m_name; }

	virtual void speak() const
	{
		cout << m_name << " ??? " << endl; 
	}
};

class Cat :public Animal 
{
public:
	Cat(string name)
		:Animal(name) {

	}

	void speak() const
	{
		cout << m_name << " Meow " << endl;
	}
};


class Dog :public Animal
{
public:
	Dog(string name)
		:Animal(name) {

	}

	void speak() const
	{
		cout << m_name << " Woof " << endl;
	}
};
int main() {

	Animal a("Animal");
	Dog d("Dog");
	Cat c("Cat");

	//자식클래스를 부모클래스의 포인터로 캐스팅해서 사용하면
	//자신이 부모클래스인줄 알고 작동한다.
	a.speak();
	d.speak();
	c.speak();

	Animal *a1 = &d;
	Animal *a2 = &c;


	//활용하는 경우
	Cat cats[] = { Cat("cat1"),Cat("cat2"), Cat("cat3"), Cat("cat4"), Cat("cat5") };
	Dog dogs[] = { Dog("dog1"), Dog("dog2") };
	//위에껄 다 확인해볼려면 for문을 사용해야한다.

	Animal *my_animals[] = { &cats[0],&cats[1], &cats[2], &cats[3], &cats[4], &dogs[0], &dogs[1] };

	//부모클래스의 메소드가 실행된다.
	//virtual 을 붙이면 자식클래스인것처럼 실행한다.
	//이런 성질을 다형성이라고 한다.
	for (int i = 0; i < 7; i++)
		my_animals[i]->speak();


	return 0;
}

상속받은 함수를 오버라이딩하기

상속을 사용하는 일반적인 경우엔

상속을 해주는 부모클래스와 상속을 받는 자식클래스는
보통 기능차이가 많지않을 수 있다.

이때 함수오버라이딩을 유용하게 사용할수 있다.

함수 오버라이딩할때 부모클래스의 함수를 사용하고 싶다면 부모클래스이름은 선언한다.

Base::Print();


다형성에서 사용된다.

<< operator 를 사용하고 싶으면 static_cast해서 사용한다.

out << static_cast<Base>(b) << endl;

 

#include <iostream>

using namespace std;

class Base {
protected:
	int m_i;

public:
	Base(int a)
		: m_i(a)
	{

	}

	void Print() {
		cout << "I'm  Base" << endl;
	}

	friend std::ostream & operator << (std::ostream & out, const Base &b) {
		out << "Base opertator";
		return out;
	}
};

class Derived : public Base {
public:
	double m_d;

	Derived(int a)
		:Base(a) {

	}

	void Print() {
		Base::Print();
		cout << "I'm  Derived" << endl;
	}

	friend std::ostream & operator << (std::ostream & out, const Derived &b) {
		out << static_cast<Base>(b) << endl;
		out << "Derived opertator";
		return out;
	}
};

int main()
{
	Base b(5);
	Derived d(2);

	b.Print();
	d.Print();
	cout << b << endl;
	cout << d << endl;
	return 0;
}

상속과 접근지정자

클래스에서 접근지정자로 접근권한을 제한할 수 있다.
상속도 마찬가지로 접근지정자로 제어할 수 있다.

protected는 외부에선 접근 불가능하지만 자식클래스에서 접근가능하다.

유도된 클래스(자식클래스)에 새로운 기능 추가할때
protected를 사용하면 private 변수일때 public에 getValue()를 만들어 사용하지않고 퍼포먼스를 향상시킬 수 있다.

 

#include <iostream>
using namespace std;
class Base {
protected:
	int m_public;

public:
	Base(const int & a) 
	:m_public(a){

	}
};

class Derived : public Base
{
public:
	Derived(const int & a) 
	:Base(a){
	
	}

	void setValue(int value) {
		Base::m_public + value;
	}
};
int main()
{

	return 0;
}


다중상속일때 단계가 높은 부모클래스에 접근하지 못하게할때 사용한다.

즉, private 으로 상속하면 다중상속일때 하하위 클래스가 직접접근하지 못하게한다.

 

#include <iostream>

using namespace std;

class Base {
public:
	int m_public;

	int funPublic() {
		return 0;
	}
protected:
	int m_protected;
	int funProtected() {
		return 0;
	}
private:
	int m_private;
};

class Derived : public Base
{
public:
	Derived() {
		m_public = 123;
		m_protected = 123;
		//m_private = 123;
		funPublic();
		funProtected();
	}
};

class Derived2 : protected Base
{
public:
	int a;
	Derived2() {
		m_public = 123;
		m_protected = 123;
		//m_private = 123;
		a = funPublic();
		a = funProtected();
	}
protected:
	int a2 = 0;
};

class Derived3 : private Base
{
public:
	int a;

	Derived3() {
		m_public = 123;
		m_protected = 123;
		//m_private = 123;
		a = funPublic();
		a = funProtected();
	}

};

class GrandChild : public Derived3 {
public:
	GrandChild() {
		//m_public; 불가능하다
		cout << a << endl;
	}
};

int main()
{
	Derived der;

	der.m_public = 123;
	//base.m_protected = 123;
	//base.m_private = 123;
	
	//protected 상속
	Derived2 der2;
	//der.m_public = 123;

	//private 상속
	Derived3 der3;
	//der.m_public = 123;


	return 0;
}

유도된 클래스들의 생성과 초기화

부모클래스를 상속한 자식클래스의 크기를 보게되면
부모클래스의 크기까지 포함된걸 볼 수 있다.
sizeof로 확인한다. 패딩으로인해 정확한 사이즈는 안나온다.

다중상속을 하게됬을때 A > B > C 로 상속하게되면 C는 A의 생성자를 실행하지 못한다.

생성자는 부모부터 소멸자는 자식부터 실행된다. 잊지말자!

 

#include <iostream>

using namespace std;

class A
{
private:
	int m_i;

public:
	A(const int &a) :m_i(a) {
		cout << "A Constructor" << endl;
	}

	~A() {
		cout << "A Destructor" << endl;
	}

};

class B : public A
{
public:
	double m_d;
	B(const int & i, const double &b)
		: A(i), m_d(b) {
		cout << "B Constructor" << endl;
	}
	~B() {
		cout << "B Destructor" << endl;
	}
};

class C : public B
{
public:
	char m_c;
	C(const int & i, const double &b,const char & c)
		: B(i,b), m_c(c) {
		cout << "C Constructor" << endl;
	}
	~C() {
		cout << "C Destructor" << endl;
	}
};


int main()
{

	cout << sizeof(A) << endl;
	cout << sizeof(B) << endl;
	cout << sizeof(C) << endl;

	C c(1, 1.3, 'a');

	return 0;
}

유도된 클래스들의 생성순서
Derived

 

기본지식

접근지정자
private 은 자식도 사용못한다.
protected는 자식은 사용가능하다.

:initalizer list는 안된다. 이유는?
클래스가 생성되는 순서를 알아야한다.

자식클래스를 객체생성하면 부모클래스가 먼저 생성되는것을 확인할 수 있다.

debug를 해보게되면
부모객체,자식객체변수를 쓰레기값으로 생성되고 
부모객체부터 초기화하고 자식객체의 변수들을 초기화되는걸 볼 수 있다. 

자식클래스는 부모클래스에 있는걸 다 사용할 수 있기에
부모클래스부터 정의해서 사용할 수 있게한다.

부모클래스의 constructor를 항상 먼저 실행시킨다.

다중상속을 하여도 맨위의 부모클래스부터 연쇄적으로초기화한다.

소멸자 Destructor는 반대로 소멸된다. 자식부터 소멸된다.

 

아래코드의 생성 순서를 보자(주석으로 써놓았다.)

1.객체생성한다.

2. 자식클래스 생성자로 온다.

3.부모클래스 생성자를 실행한다.

4.자식클래스의 생성자를 초기화한다.

 

#include <iostream>

using namespace std;

class Mother
{
public:
	int m_i;
	//3.부모클래스 생성자를 실행한다.
	Mother() :m_i(1){
		cout << "Mother Constructor" << endl;
	}
	~Mother() {
		cout << "Mother Destructor" << endl;
	}
	Mother(const int &a) :m_i(a) {
		cout << "Mother Constructor" << endl;
	}
};

class Child : public Mother 
{
public:
	double m_d;
	//2. 자식클래스 생성자로 온다.
	Child()
	: //내부적으로 숨어있다.Mother(),
		//4.자식클래스의 생성자를 초기화한다.
		m_d(1.0){
		cout << "Child Constructor" << endl;
	}
	~Child() {
		cout << "Child Destructor" << endl;
	}
};


class A : public Child
{
public:
	A() {
		cout << "A" << endl;
	}
	~A() {
		cout << "A Destructor" << endl;
	}
};
int main()
{
	//1.객체생성
	Child c1;
	
	return 0;
}

Inheritance (is-a relationship)

상속이 도움되는 이유를 구체적인 사례를 보자.

학생,교수 클래스 모두 이름이 있다.
학생,교수의 공통점은 사람이다.

사람의 기본적인 데이터(이름)를 부모클래스로 생성한다.
즉, 중복되는 데이터만 부모클래스로 뽑아낸다.

부모클래스만 사용하는기능은 부모클래스에 정의한다.
set,get등이 있다.

부모클래스의 기능을 사용가능한건 this로 확인할 수 있다.

중복되는 기능을 유지보수할때 부모클래스만 수정하면되게된다.

 

아래코드는 교수,학생클래스를 생성할때 공통된 데이터인

이름을 부모클래스로 생성해 상속받는다.

 

Person.h

#pragma once
#include <string>
#include <iostream>

class Person 
{
private:
	std::string m_name;

public:
	Person(const std::string & name) 
	:m_name(name) {}

	void setName(const std::string & name) {
		m_name = name;
	}

	std::string getName() const{
		return m_name;
	}

	void doNothing() const
	{
		std::cout << m_name << " doNothing" << std::endl;
	}
};

Student.h

#pragma once

#include "Person.h"

class Student : public Person{
private:
	int m_intel;

public:
	Student(const std::string & name = "noName", const int & intel = 0)
		: Person(name), m_intel(intel) {}

	void setIntel(const int & intel) {
		m_intel = intel;
	}

	int getIntel()
	{
		return m_intel;
	}

	friend std::ostream & operator << (std::ostream & out, const Student & s) {
		out << s.getName() << " " << s.m_intel;
		return out;
	}
};

Teacher.h

#pragma once

#include "Person.h"

class Teacher :public Person
{
private:


public:
	Teacher(const std::string & name = "noName")
		:Person(name) {

	}

	friend std::ostream & operator << (std::ostream & out, const Teacher & t1) {
		out << t1.getName();
		return out;
	}

};

main.cpp

#include "Student.h"
#include "Teacher.h"

using namespace std;

int main()
{
	string name = "";
	Student s("Jack Jack");
	Teacher t("Choi");

	cout << s.getName() << endl;
	cout << t.getName() << endl;

	s.doNothing();
	t.doNothing();

	return 0;
}

객체지향의 핵심
is-a relationship
inheritance

자식클래스는 상속받은 부모클래스의 기능을 모두 사용할 수 있다.
상속을 받은 클래스(자식클래스)를 derived class라고도 한다.

여러클래스에 일반화된것들을 뽑아서 부모클래스로 생성한다.
즉, 여러클래스에서 재사용이 매우용이하다.

부모클래스,자식클래스에 이름이 같은 메소드가 있다면 자식클래스의 메소드가 실행된다.
private는 자식에게도 허용이안된다. 이럴때 protected를 사용거나 부모클래스 생성자를 사용한다.

자식클래스의 생성이유는 부모클래스의 기능과 자식클래스의 기능을 합쳐쓰기 위함이다.

자식클래스에서 생성자Constructor를 만들려면 부모클래스를 불러와 정의해준다.

당연히 자식클래스에서 부모클래스를 사용할수 있기 때문에

부모클래스가 먼저생성되고 자식클래스가 생성된다. 

즉, 자식클래스가 생성될때 부모클래스의 생성자를 같이 실행한다.

즉, 기본생성자가 없으면 정의 해주어야한다.
아니면 자식클래스 생성자에서 부모클래스생성자를 선언해준다.

 

#include <iostream>

using namespace std;

class Mother {
private:
	int m_i;

public:
	//Mother(){}

	Mother(const int & i_in) 
	: m_i(i_in) {
		cout << "constructor" << endl;
	}

	void setValue(const int & i) {
		m_i = i;
	}

	int getValue() {
		return m_i;
	}
};

class Child : public Mother
{
private:
	double m_d;

public:
	Child(const double & d_in, const int & i_in) 
	: Mother(i_in),m_d(d_in)
	{}

	void setValue(const double & d_in,const int & i_in) {
		Mother::setValue(i_in);
	}

	void setValue(const double & d) {
		m_d = d;
	}

	double getValue() {
		return m_d;
	}
};

//Mother 클래스 재사용
class Daughter : public Mother
{

};

int main()
{
	Mother mother(11);
	mother.setValue(1234);
	cout << mother.getValue() << endl;

	Child child(12,222);
	cout << child.getValue() << endl;
	cout << child.Mother::getValue() << endl;

	return 0;
}

컨테이너클래스 Container Classes

다른클래스를 담는 역할을하는 클래스를 컨테이너 클래스라고한다.

vertor,array등이 있다.

IntArr 클래스를 한번 만들어보자.

 

#include <iostream>
#include <vector>
#include <array>
#include <cassert>
#include <initializer_list>

using namespace std;

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

	int beforeLen = 0;
	int *beforeData = nullptr;

public:
	void ixCheck(const int & ix) {
		assert(ix <= m_length);
		assert(ix >= 0);
	}

	//Constructor
	IntArr() {}

	IntArr(const int & len) 
	{
		assert(len >= 0);
		m_length = len;
		m_data = new int[m_length];
	}

	IntArr(const initializer_list<int> & list) 
	{
		m_length = list.size();
		m_data = new int[m_length];
		int a = 0;
		for (auto & ele : list) {
			m_data[a] = ele;
			a++;
		}
	}
	//Destrurctor
	~IntArr() {
		delete[] this -> m_data;
	}

	//initialize()
	IntArr & operator = (const initializer_list<int> & list) {
		delete[] m_data;
		m_length = list.size();
		m_data = new int[m_length];
		
		if (m_data != nullptr) {
			int a = 0;
			for (auto & ele : list) {
				m_data[a] = ele;
				a++;
			}
		}
		else {
			m_data = nullptr;
		}
		return *this;
	}

	int getSize() {
		return m_length;
	}

	

	void copyArr() {
		beforeLen = m_length;
		beforeData = new int[beforeLen];
		for (int i = 0; i < beforeLen; i++) {
			beforeData[i] = m_data[i];
		}
	}
	//reset()
	void reset() {
		m_length = 0;
		m_data = nullptr;
	}

	//resize()
	void resize(const int & ix) {
		this -> ixCheck(ix);
		this -> copyArr();

		m_length = ix;
		m_data = new int[m_length];

		for (int i = 0; i < m_length; i++) {
			m_data[i] = beforeData[i];
		}

		delete[] beforeData;
	}
	//insertBefore(const int & value, const int & ix);
	void insertBefore(const int & value, const int & ix) {
		this->ixCheck(ix);
		this->m_data[ix] = value;
	}
	//remover(const int & ix);
	void remover(const int & ix) {
		this->ixCheck(ix);
		this->copyArr();

		m_length = beforeLen - 1;
		m_data = new int[m_length];

		int count = 0;
		for (int i = 0; i < beforeLen; i++) {
			if (i != ix) {
				m_data[count] = beforeData[i];
				count++;
			}
		}

		delete[] beforeData;

	}

	IntArr & push_back(const int &val) {
		this->copyArr();

		m_length = m_length + 1;
		m_data = new int[m_length];

		for (int i = 0; i < m_length; i++) {
	
			if (m_length - 1 == i) {
				m_data[i] = val;
			}
			else {
				m_data[i] = beforeData[i];
			}
			
		}
		delete[] beforeData;

		return *this;
	};

	friend ostream & operator << (ostream & out, IntArr &iA) {
		for (int i = 0; i < iA.m_length; i++) {
			
			out << iA.m_data[i] << " ";
		}
		return out;
	}
};

int main()
{
	IntArr arr{ 1,2,3,4 };
	cout << arr << endl;
	cout << arr.getSize() << endl;

	arr = { 1,2,3 };
	cout << arr << endl;
	cout << arr.getSize() << endl;

	arr.resize(2);
	cout << arr << endl;
	cout << arr.getSize() << endl;

	arr.remover(2);
	cout << arr << endl;
	cout << arr.getSize() << endl;
	arr.insertBefore(100, 0);
	cout << arr << endl;
	cout << arr.getSize() << endl;

	arr.push_back(1).push_back(3);
	cout << arr << endl;
	cout << arr.getSize() << endl;

	return 0;
}

의존관계 Dependencies

서로간의 연결 강도가 낮다.

 

ex:자바 스프링에서 여러기능을 추가할때 사용한다.

재사용이 가능한 클래스를 어느 클래스에서 사용할때를 말한다.

다른 클래스를 사용하더라도 그 클래스의 자세한 내용은 몰라도된다.
즉,잠시 빌려 사용한다고 생각하면된다.

main.cpp

#include "Worker.h"

using namespace std;

int main()
{
	Worker w;
	w.doSomething();

	return 0;
}

Timer.h

#pragma once
#include <chrono>
#include <iostream>

using namespace std;

class Timer {

	using clock_t = chrono::high_resolution_clock;
	using second_t = chrono::duration<double, ratio<1>>;

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

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

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

Worker.h

#pragma once

class Worker {
public:
	//doSomething에서 Timer클래스를 사용한다.
	//하지만 여기서 사용하는지 알 수 없다.
	void doSomething();
};;

Worker.cpp

#pragma once
#include "Worker.h"
#include "Timer.h"


void Worker::doSomething() {
	//잠시 Timer Class의 기능을 사용한다.
	Timer timer;
	timer.elapsed();
}

제휴관계 Association

어느 한쪽이 주 반대쪽이 부가 되는 개념이 아닌 개념이다.
어느쪽이든 주,부가 될수 있다.

다른관계들보단 많이 사용하지 않는다.

서로가 서로를 사용한다. 용도이외에는 무관하다.

의사,환자

의사1이 환자1을 만난다.
환자1이 의사1를 만난다.
의사1이 환자2를 만난다.
환자2가 의사1을 만난다.

즉, 서로 기록은 하지만 터치하지 못한다.
또 양방향으로 기록하는게 아닌 단방향으로 기록할 수 있다.

 

#include <iostream>
#include <vector>
#include <string>

using namespace std;

class Doctor;

class Patient {
private:
	string m_name;
	vector<Doctor*> m_doc;

public:
	Patient(string name)
		:m_name(name) {

	}

	void addDoc(Doctor *new_doc) 
	{
		m_doc.push_back(new_doc);
	}

	void meetDot();
	friend class Doctor;
};

class Doctor {
private:
	string m_name;
	vector<Patient*> m_pat;
	
public:
	Doctor(string name)
		:m_name(name) {

	}

	void addPai(Patient *new_pai)
	{
		m_pat.push_back(new_pai);
	}

	void meetPai() {
		for (auto & ele : m_pat) {
			cout << m_name << " - >Meet Pat : " << ele->m_name << endl;
		}
	}
	friend class Patient;
};
void Patient::meetDot() {
	for (auto & ele : m_doc) {
		cout << m_name << " - >Meet Doc : " << ele->m_name << endl;
	}
}
int main()
{
	Patient *p1 = new Patient("choi");
	Patient *p2 = new Patient("lee");
	Patient *p3 = new Patient("kim");

	Doctor *d1 = new Doctor("D_kim");
	Doctor *d2 = new Doctor("D_jung");

	p1->addDoc(d1);
	d1->addPai(p1);
	p2->addDoc(d1);
	d1->addPai(p2);
	p1->meetDot();
	p2->meetDot();
	d1->meetPai();
	delete p1;
	delete p2;
	delete p3;

	delete d1;
	delete d2;
	return 0;
}

+ Recent posts