티스토리 뷰

#include<iostream>

using namespace std;

class Base
{
	protected:
	int m_value;
	
	public:
	Base(int value)
		: m_value(value)
	{
	}
	
};

class Derived : public Base
{
	public:
	Derived(int value)
		: Base(value)
	{
	}
	
	void setValue(int value)
	{
		Base::m_value = value;
		// do some work with the variables defined in Derived
	}
};

 

11.7

 

#include<iostream>

using namespace std;

class Base
{
	protected:
	int m_value;
	
	public:
	Base(int value)
		: m_value(value)
	{
	}
	
	void print()
	{
		cout << "I'm base" << endl;
	}
};

class Derived : public Base
{
	public:
	Derived(int value)
		: Base(value)
	{
	}
	
	void setValue(int value)
	{
		Base::m_value = value;
		// do some work with the variables defined in Derived
	}
	
	void print()
	{
		cout << "I'm derived" << endl;
	}
};

int main()
{
	Base base(5);
	base.print();
	
	Derived derived(7);
	derived.print();
	
	return 0;
}

// I'm base
// I'm derived

 

Derived의 경우 print함수가 두가지이다.

 

Base에서 가져오는 print함수 그리고 Derived 내부의 print함수.

 

이름을 바꾸면 되지 않느냐? 라고 생각할 수 있지만, 그러지 않는 이유는 다형성 때문이다.

 

#include<iostream>

using namespace std;

class Base
{
	protected:
	int m_value;
	
	public:
	Base(int value)
		: m_value(value)
	{
	}
	
	void print()
	{
		cout << "I'm base" << endl;
	}
	
	friend std::ostream & operator << (std::ostream & out, const Base &b)
	{
		cout << "This is base output" << endl;
		return out;
	}
};

class Derived : public Base
{
	public:
	Derived(int value)
		: Base(value)
	{
	}
	
	void setValue(int value)
	{
		Base::m_value = value;
		// do some work with the variables defined in Derived
	}
	
	void print()
	{
		Base::print();
		cout << "I'm derived" << endl;
	}
	
	friend std::ostream & operator << (std::ostream & out, const Derived & b)
	{
		cout << static_cast<Base>(b);
		cout << "This is derived output" << endl;
		return out;
	}
};

int main()
{
	Base base(5);
	cout << base;
	
	Derived derived(7);
	cout << derived;
	
	return 0;
}

// This is base output
// This is base output
// This is derived output

 

Derived는 내부의 Base를 가지고 있기때문에 static_cast가 가능하다.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/01   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함