8.11(토) C# - 기초문법3

from Study/C# 2007/08/13 17:16 view 20050

using System;

using System.Reflection;    // c# reflect 서비스

 

// Reflection 메타데이타 에서 정보를 얻어온다.

class Point

{

    public int x;

    public int y;

 

    public void foo() { }

}

 

class Test

{

    public static void Main()

    {

        Point p = new Point();

 

        Type t = p.GetType();   // p type 정보를 담고 있는 객체를 얻는다.

                                // RTTI, RTCI(MFC)

        Console.WriteLine("{0}", t.FullName);

        Console.WriteLine("{0}", t.BaseType.FullName);

 

        // t 모든 메소드 정보를 배열로 얻어 온다.

        MethodInfo[] mis = t.GetMethods();

 

        // 배열의 모든 요소를 열거하면서 출력한다.

        foreach (MethodInfo m in mis)

        {

            Console.WriteLine("{0}, {1}", m.Name, m.ReturnType);

        }

    }

}

 

////////////////////////////////////////////////////////////////////////
// Monostate : static
멤버 data static 멤버 변수만 가진 클래스 객체를
              만들 필요가 없다.

class Math

{

    //private Math() { }

    public static int plus(int a, int b) { return a + b; }

}

Math.plus(1, 2);

 


///////////////////////////////////////////////////////////////////////////
//
델리게이트 선언

delegate void CrashHandler( int a );

// 선언을 보고 C#컴파일러가 CrashHandler라는 클래스를 생성해 준다.

// 내부적으로 void 리턴하고 int 인자가 1개인 함수 포인터를 관리해주는 클래스.

 

class Car

{

    public int speed = 0;

    public CrashHandler handler;    // 델리게이터의 참조

 

    public void SetSpeed(int n)

    {

        speed = n;

        if (handler != null)

            handler.Invoke(n);  //handler(n);  // 외부에 알린다.

    }

}

 

class Test

{

    public static void foo(int a)

    {

        Console.WriteLine("Test::foo - {0}", a);

    }

    public static void Main()

    {

        Car c = new Car();

 

        c.handler = new CrashHandler(Test.foo);

        c.handler += new CrashHandler(Test.foo);

 
        c.SetSpeed(100);

    }

}

 

Tag |

8.11(토) C# - 기초문법2

from Study/C# 2007/08/13 17:12 view 26874

using System;

 

// C++ 다른 C# 핵심 문법들

 

// 1. Property : 구현자 입장에서는 함수(제어문 가능)

//               사용자 입장에서는 Data처럼 보인다.

// 2. indexer : C++ 배열 연산자 재정의..

 

class Bike

{

    private int gear;

    private int[] array = new int[10];  // C# 배열 만드는 .

 

    public int Gear

    {

        get { return gear; }

        set {  if( value < 100 ) gear = value; }

    }

 

    public int this[int name]   // set_Item( name, value ) 함수로 제공된다.

    {

        get { return array[name]; }

        set { array[name] = value; }

    }

}

 

class Test

{

    public static void Main()

    {

        Bike p = new Bike();

        p.Gear = 10;

 

        Console.WriteLine("{0}", p.Gear);

    }

}


//////////////////////////////////////////////////////
// out
파라미터와 Ref 파라미터

// 결국 항상 C처럼 메모리 그림을 그려서 해결하면 됩니다.

 

class Point

{

    public int x;

}

 

class Test

{

    public static void foo(out Point p)

    {

        //p.x = 20;

 

        p = new Point();

 

        p.x = 100;

    }

 

    public static void Main()

    {

        Point p1 = new Point();

        p1.x = 10;

 

        foo(out p1);

 

        Console.WriteLine("{0}", p1.x);

    }

}

 

class Test

{

    public static void foo(out int a)

    {

        a = 20;

    }

    public static void Main()

    {

        int x = 10;

        foo(out x);

 

        Console.WriteLine("{0}", x);

    }

}

 

//////////////////////////////////////////////////////////
//
결국 C++ : type 사용자가 메모리의 위치 결정

//      C#  : type 제작자가 메모리의 위치 결정

 

// 무조건 참조 type이다.

class Point1

{

    public int x;

    public int y;

}

 

// 구조체는 무조건 type이다. stack 객체가 만들어 진다.

struct Point2

{

    public int x;

    public int y;

}

 

class Test

{

    public static void Main()

    {

        Point1 p1;  // 참조 뿐이다.

        Point2 p2;  // 객체이다.

 

        Point1 p3 = new Point1();   // 힙에 만든다.

        Point2 p4 = new Point2();   // stack 만든다.

 

        // int 구조체이다.

        int a;

 

        Point1 pp;  // 실제 Point1 아니고 C++ 포인터개념이다.
                    // (C#
에서는 레퍼런스라고 한다.)

 

        //Point1 p = new Point1;  // C++

        Point1 p = new Point1();  // C#

 

        int a = 0;

        int b = new int();

    }

}

Tag |

8.11(토) C# - 기초문법1

from Study/C# 2007/08/13 17:06 view 21699

using System;   // using namespace System 의미


// 1. Main 함수의 기본 모양

// 2. Console 클래스의 static 함수들을 사용해서 표준 입출력을 처리한다.

// 3. %d 대신 {0}, {1} 사용.

// 4. 모든 것은 객체이다. 결국 Object 자식이다.
class Test

{

    public void foo()

    {

    }

 

    public static void Main()

    {

        int a = 10;

        int b = 20;

 

        Console.WriteLine("a= {0} {1} {0}", a, b);

    }

}

 

///////////////////////////////////////////////////////////////
//
주제 2. 모든 것은 객체이다. 그리고 모든 것은 Object 자식이다.

class Point

{

    public int x = 0; // 필드 초기화 가능

    public int y = 0; // 필드 초기화 가능

    public Point( int a, int b )

    {

        x = a;

        y = b;

    }

 

    // 부모인 Object ToString() 멤버 함수를 재정의 한다.

    // C# 가상함수 재정의시 override 키워드를 사용한다.

    public override string ToString()

    {

        return "[Point]";

    }

}

 

class Test

{

    public static void Main()

    {

        int a = 10; // int 별명에 불과하다.

 

        System.Int32 b = 0;

 

        Console.WriteLine("{0}", a);

 

        Point p = new Point(1, 1); // 주의 C++ new Point;

 

        Console.WriteLine("{0}", p.ToString());

    }

}

Tag |

8.10(금) C++ 디자인패턴 - 정의

from Study/C++ 2007/08/13 16:49 view 27198

1.     오직 한 개만 만들수 있는 객체 -> 싱글톤

2.    
자신의 사본을 만드는 가상함수 -> Prototype

3.    
data의 변화를 여려명에 알려주자 -> Observer, MFC( Doc/View )

4.     기존 클래스의 인터페이스만 변경해서 다른 클래스처럼 보이게 한다.->Adapter, STL stack

5.     그릇은 그릇과 객체를 모두 담을 수 있다. -> Composite ****

6.     객체에 포장을 한다. 포장 후 다시 포장이 가능하다.
      
기본 기능을 하는 객체와 그 기능을 쉽게 사용    할 수 있게 하는 객체가 있다. -> Decorator

7.     객체를 만드는 공장을 짓자. ? Factory

8.     Collection의 모든 요소를 열거하는 객체 -> 반복자

9.     Collection 내부를 떠돌아 다니는 객체 -> Visitor ( 하나씩을 돌아다니며 변경 )

10.   기존 객체를 데신하는 역할의 객체를 만들자 -> Proxy

11.   작고 여러 개 만들어지는 객체는 공유해서 사용하자. -> fly weight

12.   프로그램의 전체 틀을 미리 설계해 놓자. ? Application Framework( 창시자 책 )

13.   책임을 다른 곳에 전달해서 하나의 문제를 여러객체가 처리 할수 있도록 하자.
      책임전가 ? Chain of Responsibility

14.   알고리즘 자체를 캡슐화 하면 변경이 쉬워 진다. ? 전략 패턴

15.   부모에 비가상함수로 알고리즘을 자식에 protected 가상함수로 알고리즘의 구현을 제공하자.
      template method(
메뉴, 아이스크림 )

16.   객체에 사건이 발생시 외부에 전달하는 기법 ? callback, event, signal

Tag | ,

#include <iostream>

#include <memory>

#include <string>

#include <vector>

#include <conio.h>

using namespace std;

using namespace std::tr1;

 

#define interface struct

#define clrscr()  system("cls")

 

//***************************************

//     IMenuHandler

//***************************************

interface IMenuHandler

{

       virtual ~IMenuHandler() {}

       virtual void OnCommand( unsigned int id ) = 0;

};

//***************************************

//     AbstractMenu

//***************************************

class AbstractMenu

{

       string title;

public:

       AbstractMenu( string s) : title(s) {}

       virtual ~AbstractMenu() {}

       virtual string GetTitle() const { return title;}

       virtual void Command() = 0;

};

//***************************************

//     MenuItem

//***************************************

class MenuItem : public AbstractMenu

{

       unsigned int id;

       IMenuHandler* pMenuHandler;

public:

       MenuItem( string s, unsigned int i, IMenuHandler* pHandler)

             : AbstractMenu(s), id(i), pMenuHandler(pHandler) {}

       virtual void Command() { pMenuHandler->OnCommand( id );     }

};

//***************************************

//     PopupMenu

//***************************************

class PopupMenu : public AbstractMenu

{

       typedef shared_ptr<AbstractMenu> PAbstractMenu;

       vector<PAbstractMenu> menu_list;

       bool isroot;

 

       typedef list<Tape*> TapeList;     // 테입 리스트를 명확하게 표현 해준다.

public:

       static string str_exit;

       static string str_goback;

 

       int xpos, ypos; // 현재 팝업 메뉴가 나타 날 위치로 메뉴를 뜨게 해준다.!!

 

public:

       PopupMenu(string s, bool b = false) : AbstractMenu( s ), isroot(b) {}

       void Append(AbstractMenu* m) { menu_list.push_back( (PAbstractMenu)m);}

 

       virtual void Command()

       {

             while( 1 )

             {

                    clrscr();

                    size_t cnt = menu_list.size();

                    for ( size_t i = 0; i < cnt; ++i )

                           cout << i + 1 << ". " <<
                                 menu_list[i]->GetTitle() << endl;

 

                    cout << cnt + 1 << ". " <<
                                 ( isroot ? str_exit:str_goback) << endl;

 

                    unsigned int cmd;

                    cout << "메뉴를선택하세요>> ";

                    cin >> cmd;

 

                    // 문자를 입력 한 경우

                    if ( cin.fail() )

                    {

                           cin.clear();

                           cin.ignore(256, '\n');

                           continue;

                    }

                    if ( cmd < 1 || cmd > cnt + 1 ) continue;

                    if ( cmd == cnt + 1 ) return ;

                    menu_list[cmd-1]->Command();

             }

       }

};

string PopupMenu::str_exit = "종료";

string PopupMenu::str_goback = "이전메뉴로";

 

//---------------------------------------------

// Menu Class 활용 예제..

class VideoShop : public IMenuHandler

{

       shared_ptr<PopupMenu> pMenuBar;         // video shop의 메인 메뉴

public:

       VideoShop() : pMenuBar( new PopupMenu("ROOT", true))

       { }

 

       virtual void OnCommand( unsigned int id )

       {

             cout << id << " 메뉴가선택됨" << endl;

             getch();

       }

 

       void InitMenu()

       {

             // initialize menu

             PopupMenu* p1 = new PopupMenu( "고객관리" );

             p1->Append( new MenuItem( "고객등록", 1, this ));

             p1->Append( new MenuItem( "고객삭제", 2, this ));

             p1->Append( new MenuItem( "기타",      3, this ));

 

             PopupMenu* p2 = new PopupMenu( "Tape 관리" );

             p2->Append( new MenuItem( "Tape 등록", 11, this ));

             p2->Append( new MenuItem( "Tape 삭제", 12, this ));

             p2->Append( new MenuItem( "기타",      13, this ));

            

             PopupMenu* p3 = new PopupMenu( "대여관리" );

             p3->Append( new MenuItem( "대여등록",   21, this ));

             p3->Append( new MenuItem( "반납",       22, this ));

             p3->Append( new MenuItem( "기타",       23, this ));

 

             pMenuBar->Append( p1 );

             pMenuBar->Append( p2 );

             pMenuBar->Append( p3 );

 

             PopupMenu::str_exit = "Exit";

             PopupMenu::str_goback = "Go Back";

       }

 

       void Start()

       {

             InitMenu();

             pMenuBar->Command();

       }

};

 

int main()

{

       VideoShop vs;

       vs.Start();

} 

Tag | ,

8.10(금) QT - 설치와 사용법

from Study/QT 2007/08/13 16:33 view 25721
mingw513.exe
qt-win-opensource-src-4.3.1.zip

인스톨링~!

more..


도움 될 만한 것들.

more..


Tag |

8.9(목) C++ - Proxy의 활용

from Study/C++ 2007/08/13 16:00 view 42692

#include <iostream>

using namespace std;

// C# : .Net Remoting

// JAVA : RMI

// COM : 분산COM

// 원격제어에 있는 메소드를 호출하겠다.

// proxy ( foo(1, 2) ) -> 마샬리-> 스텁-> 서버측 foo호출

 

// proxy를 제대로 써보자.

class Printer

{

public:

       Printer()

       {

             cout << "Warming up" << endl;

             for ( int i = 0; i < 1000000000; ++i );

             cout << "OK..." << endl;

       }

 

       void print() const

       {

             cout << "Printer::print" << endl;

       }

       void print_time() const

       {

             cout << "print_time()" << endl;

       }

};

 

// printer를 대신 할 proxy를 만든다.

// 대행자를 만들어서 사용하도록 하자.

class PrinterProxy

{

       Printer* p;

public:

       void print_time() const

       {

             cout << "print_time()" << endl;

       }

       void print() const

       {

             // 진짜 객체가 필요하면 만들어서 사용한다.

             if ( p == 0 )

                    p = new Printer;

             p->print();

       }

};

 

 

void main()

{

       Printer p;

       p.print_time();

}

 

Tag |

8.9(목) C++ 디자인패턴 - Bridge

from Study/C++ 2007/08/13 15:56 view 31218

#include <iostream>

using namespace std;

 

// Bridge 패턴: 인터페이스와 구현을 분리한다.

 

// 모든 MP3 player의 인터페이스

struct MP3PlayImp

{

       virtual void Play() = 0;

       virtual void Stop() = 0;

};

 

// 결국 인터페이스와 구현을 분리하는 개념.

// 사용자는 playstop만 가져다 쓰면 되고

// 제공자는 class만 제공하면 되도록 해야 한다.!!!

// 실제 GUI기능을 갖춘 MP3 Player 클래스

class MP3Play

{

       MP3PlayImp* pImp;

public:

       void Play()

       {

             // 위임(Delegate)라고 한다. - 구현물을 쉽게 바꿀수 있다.

             // PIMP 라는 개념.

             PImp->Play();

       }

 

       void Stop()

       {

             PImp->Stop();

       }

};

 

void main()

{

       // MP3 사용자

       MP3Play p;

       p.Play();

       p.Stop();

}

 


//////////////////////////////////////////////////////////
// linked list
를 만들고 싶다. 값을 추가하는 함수를 만들고 싶다.

// 함수 이름을 무엇으로 할까?

 

// 실제 list의 구현물( 구현의 클래스 )

class real_list

{

public:

       void real_push_front( int a ) { }

       void real_push_back( int a ) { }

};

 

// 내부구현이다른list

class real_list2

{

public:

       void real_push_front( int a )

       {

             //전혀 다른 기법을 사용한다.

       }

       void real_push_back( int a )

       {

             //전혀 다른 기법을 사용한다.

       }

};

 

// 인터페이스 클래스

class list

{

       real_list* st;

public:

       void push_front( int a ) { st->real_push_front(a); }

       void push_back( int a )  { st->real_push_back(a); }

};

 

Tag | ,

#include <iostream>

using namespace std;

 

// FlyWeight 디자인패턴: 작은객체를 공유하는 기법

//               동일한 상태를 가지는 객체는 메모리에 한번만 놓이게 한다.

//               Factory를 사용하게 된다. 또한 Factory는 주로 Sigletone이 된다.

// 객체를 만드는 클래스를 만들어 주자.(생성자를 private로 숨기는 대신)

 

class BigChar

{

       char c;

       BigChar( char a ) : c (a) { }

public:

       void Show() const { cout << "[[[[ " << c << " ]]]]" << endl; }

      

       friend class BigCharFactory;

};

 

#include <map>

 

// BigChar를 생성하는 공장을 만들자.(오직 한 개.싱글톤)

class BigCharFactory

{

       map<char, BigChar*> pool;

       BigCharFactory() {}

 

public:

       static BigCharFactory& GetInstance()

       {

             static BigCharFactory _instance;

             return _instance;

       }

 

       BigChar* CreateBigChar( char c )

       {

             if ( pool[c] == 0 )

                    pool[c] = new BigChar(c);

 

             return pool[c];

       }

 

       void Reset() // 또는 Clean()

       {

             // map에 있는 모든 객체를 제거한다.

       }

 

       void Remove( char c )

       {

       }

};

// Helper Macro 함수

BigChar* CreateChar( char c )

{

       return BigCharFactory::GetInstance().CreateBigChar(c);

}

 

void foo()

{

       BigChar*  p = CreateChar('c');

 

       cout << p << endl;

}

 

void main()

{

       BigChar* p = CreateChar('c');

       cout << p << endl;

 

       foo();

}

Tag | ,

8.9(목) C++ - 예외이야기

from Study/C++ 2007/08/12 21:19 view 21312

#include <iostream>

using namespace std;

 

// 예외이야기- 진짜 예외는 객체를(클래스) 만들어서 계층화 해야 한다.

// 예상치 않은 에러가 난다면 설계가 잘못된 것.(사용자가 지정하지 않은 에러)

// 롤백- 예외 발생시 다시 안전된 상태로 돌려놔야 한다.

 

class Exception {};

class StackException : public Exception {};

class StackUnderflowException : public StackException {};

 

// 예외 안전성의 개념

// 1. 기본보장: 예외 처리후 메모리등의 리소스낭비는 없지만 프로그램의 상태를 알
                        수는 없다
.

// 2. 강력보장: 예외를 처리한 후 프로그램의 상태가 예외발생 이전으로 복구된다.

// 3. 완전보장: 예외가없다. int a = 10;

 

// 예외중립( Exception neutral )

// exceptional c++
http://cafe.naver.com/cppmaster/1516


class
Test

{

       int buf[100];

public:

       Test() { throw 1; }

};

 

void main()

{

       try

       {

       Test* p = new Test; // 1. 메모리할당

                           // 2. 생성자호출- 그런데예외가나왔다.

       // (1)에서 할당한 메모리는 해지되었을까?? 낭비인가??

       // new 자체에서 에러 발생시 낭비를 방지하는 코드가 있다.

       }

       catch( int )

       {

       }

}

 

void foo() // 어떠한 예외라도 나올 수 있다. 예외가 없다는 throw()를 붙여줘야 한다.

{

       try

       {

             char* p = new char;

       }

       catch( std::bad_alloc e )

       {

             // 어떻게 처리할까?

             // 1. 메모리를 재할당해서 성공할 수 있다면 ok.

             // 2. 그렇지 않다면 호출자에게 다시 전달.. - 예외중립

             throw;

       }

}

 

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

// 아래 대입 연산자가 예외안전성을 지원하는가?

class String

{

       char* buff;

       int sz;

public:

 

       String& operator=( const String& s )

       {

             if ( &s == this ) return *this;

            

             char* temp = new char[ s.sz+1 ]; // 예외가 발생 할 수도 있다.

 

             strcpy( buff, s.buff );

 

             // 예외가 발생하지 않는 코드(강력보장)는 나중에 수행하자.

             delete[] buff;      // 예외가 없다.

             buff = temp;

             sz = s.sz;          // 예외가 없다.

 

             return *this;

       }

};

 

void main()

{

       String s1 = "hello";

       String s2 = "A";

 

       try

       {

             s1 = s2;

       }

       catch ( ... )

       {

       }

 

       cout << s1 << endl;   // 'A' 또는'hello" 가나와야한다.

}

 

class Stack

{

       int buf[10];

       int top;

public:

 

       int Pop() throw( StackUnderflowException )

       {

             if ( top < 0 )

             {

                    throw StackUnderflowException();

             }

             return buf[--top];

       }

};

 

void main()

{

       Stack s;

       try

       {

             int n = s.Pop();

       }

       catch( StackUnderflowException e )

       {

             cout << "예외처리" << endl;

       }

       // 예외를 잡아서 문제를 처리했다. 이제 stack을 계속 사용할 수 있을까?

       s.Push(10);

}

 

Tag |