7.31(화) C++ - 가상함수 활용하기

from Study/C++ 2007/08/02 14:34 view 24981

// 라이브러리내의모든클래스를표준출력과연계해서출력해보고싶다.

#include <string>

 

// 가상함수가아닌것을가상함수처럼보이게하기.

class object

{

public:

 

        virtual string ToString() const

        {

               return string("object");

        }

 

        friend ostream& operator<<( ostream& os, const object& o )

        {

               return os << o.ToString();

        }

};

 

class Point : public object

{

public:

        virtual string ToString() const

        {

               return string("Point");

        }

};

 

void main()

{

        object* pp = new Point;

        cout << *pp << endl;

 

        object o;

        cout << o << endl;

 

        Point p;

        cout << p << endl;

}

Tag |

7.31(화) C++ - 상속관계 활용하기

from Study/C++ 2007/08/02 14:00 view 23553

// 1. 부모* = &자식 
// 2. 1.이 주로 어떻게 활용 되는가??

// 장점 : 동일한 기능 부여!!, 모든 type을 저장하는 컬렉션 제공.


class object

{

};


class
Animal

{

public:

        int age;

};

 

class Dog : public Animal{};

class Cat : public Animal{};

 

// DogCat의 객체를 받기 위해서는 오버로딩으로 두번 써주지만..

// 부모를 이용하면 간단해진다.

void NewYear( Dog* p )

{

        p->age++;

}

void NewYear( Cat* p )

{

        p->age++;

}

/////////////////////////////////////////////

//void NewYear( void* p ) // 모든 type을 받을 수 있지만 구분을 못한다.(?)

void NewYear( Animal* p ) //모든 동물의 객체를 처리 할 수 있다.

{

        p->age++;

}

 
void main()

{

        Dog d;

        NewYear( &d );

 

        Cat c;

        NewYear( &c );

 

        Dog* p1 = new Dog;

//      int* p2 = new Dog;            // error

        Animal* p3 = new Dog;  // ok.. 부모* = &자식

 

        Dog d2;

        Animal& r4 = d2;       // ok.

        Animal o = d2; // ok.  liskov Substitution 리스코프의치환법칙.

}


//////////////////////////////////////////////////////////////////////////

class object

{

};


class
list

{

        struct Node

        {

               object* data;

               Node*   next;

        };

public:

        void Add( object* ob)

        {

               cout << "list::Add()" << endl;

        }

};

class Car : public object

{

};

class People : public object

{

};


// Car
전용Collection 을설계하자.

// strong type Collection - Adapter 패턴을활용해서만든것.

class Carcollection

{

        list st;

public:

        void Add( object* p ) { st.Add( p ); }

};

 

void main()

{

        Carcollection st;

 

        Car c;

        st.Add( &c );          // ok. 어짜피object의자식이다.

 

        People p;

        st.Add( &p );          // ok. Peopleobject의자식이다.

}

 

Tag |

class Base

{

public:

        void foo() { cout << "Base::foo" << endl; }

};

 

class Derived : public Base

{

public:

        using Base::foo;       // 자식에서도부모의foo를호출하겠다. 1의에러를보완!!

        void foo(int a) { cout << "Derived::foo" << endl; }

};

 

void main()

{

        Derived d;

        //d.foo();     // 1. error 부모와자식간엔오버로딩을성립하지않는다.

        d.foo();

        d.foo(10);     // 2. ok..

}

 

 

Tag |