다음 이전 차례

3. mychar class의 사용

'mychar class' 는 char 와 char * datatype의 완벽한 대체물이다. 여러분은 'mychar class' 를 char쓰는 것과 똑같은 쓰면서 더 많은 기능성을 얻을 수 있다. 여러분은 'libmychar.a' 를 include해야 하고 library 를 "C++" library들이 위치한 /usr/lib directory에 카피해야한다 ('libmychar.a'는 Appendix H에 있는 makefile에서 만들 수 있다 ). 'libmychar.a'을 사용하기 � 위해서는 여러분의 프로그램을 다음과 같이 컴파일하시오.


        g++ example.cpp -lmychar

다음 샘플코드를 보시오.
        mychar aa;

        aa = " Washington DC is the capital of USA ";

        // You can use aa.val like a 'char *' variable in programs !!
        for (unsigned long tmpii = 0; tmpii < aa.length(); tmpii++)
        {
                fprintf(stdout, "aa.val[%ld]=%c ", tmpii, aa.val[tmpii]);
        }

        // Using pointers on 'char *' val ...
        // Note: You must use a temporary local variable and assign the
        // pointer to aa.val. If you directly use aa.val and when
        // aa.val is incremented with aa.val++, then aa will go 
        // call destructor and later when aa.val is accessed that
        // will cause core dump !!
        for (char *tmpcc = aa.val; *tmpcc != 0; tmpcc++)  
        {
                // MUST use temporary variable tmpcc !! See note above.
                fprintf(stdout, "aa.val=%c ", *tmpcc);
        }

mychar class 를 정의한 완전한 예제 프로그램 "example_mychar.cpp" 은 Appendix A에 있고 mychar class 는 Appendix B에 있다.

3.1 연산자들

'mychar class'는 다음과 같은 연산자들을 제공한다.

연산자들을 사용한 예제
        mychar aa;
        mychar bb("Bill Clinton");

        aa = "put some value string";  // assignment operator
        aa += "add some more"; // Add to itself and assign operator
        aa = "My name is" + " Alavoor Vasudevan "; // string cat operator

        if (bb == "Bill Clinton")  // boolean equal to operator
                cout << "bb is eqaul to 'Bill Clinton' " << endl;

        if (bb != "Al Gore")   // boolean 'not equal' to operator
                cout << "bb is not equal to 'Al Gore'" << endl;

3.2 함수들

'mychar class'는 다음고 같은 함수들을 제공한다.

3.3 기타 함수들

기타 mychar 함수들을 여기에 모아두었다. 하지만 이것들을 사용하지는 마라. 대신 '+', '+=', '==' 등과 같은 연산자들을 사용하라. 이것들은 'mychar' class 'private'멤버들이다.

예를 들어 정수를 문자열로 바꾸기 위해서는 다음과 같이 하라.
        mychar  aa;

        aa = 34;  //연산자 ‘=’ 는 int 을 string 로 바꾼다.
        cout << "The value of aa is : " << aa.val << endl;

        aa = 234.878; // 연산자 '=' 는 float 을 string로 바꾼다.
        cout << "The value of aa is : " << aa.val << endl;

        aa = 34 + 234.878;
        cout << "The value of aa is : " << aa.val << endl;
        // aa 는 '268.878' 로 된다.
        // mychar를 cast 해야 한다.
        aa = (mychar) 34 + " Honourable President Ronald Reagan " + 234.878;
        cout << "The value of aa is : " << aa.val << endl;
        // '34 Honourable President Ronald Reagan 234.878' 로 출력된다.


다음 이전 차례