본문 바로가기

프로그램언어/C++

[c++] template Class

Suppose that you are writing a C++ program that requires two stacks--one for integer data and one for string data. You could implement these classes as follows. The implementation below isn't very good (it limits the stack to 1000 elements and it does no error checking), but it will serve as an example.



The main program would declare and use these stacks as follows:

Notice that the only difference between these classes (other than the name of the class) is the type of data that's put onto the stack. C++ allows you to define a single, template class to represent a stack of any possible datatype (including a user-defined datatype). The declaration would look like this:

The T represents the type of stack desired. The main program would declare and use the stacks as follows:

There is never an implementation file (*.cpp) for a template class. All of the member functions should be declared in the header file (in this case, table.h). The following shows how the functions for this class would be declared after the declaration of the class.



'프로그램언어 > C++' 카테고리의 다른 글

zlib 컴파일 에러발생.  (0) 2009.08.06
log4cxx 사용에 필요한 라이브러리 추출.  (0) 2009.07.31
[C++] template  (0) 2009.02.09
IRC 프로토콜의 이해  (0) 2009.02.04
gdb을 이용한 디버깅.  (0) 2008.12.22