In object-oriented program development, the Declaration of classes and their member functions is generally put in the specified header file, and the definition of member functions is put in another source file. This improves programming efficiency and information hiding. The following uses a linear table as an example.
// Seq. h
# Ifndef seq_h
# Define seq_h
Const int maxsize = 100;
Template <class T>
Class seqlist
...{
Public:
Seqlist ();
Seqlist (int A [], int N );
~ Seqlist ();
Int length ();
T get (int I );
Int locate (t x );
Void insert (int I, T X );
T Delete (int I );
Void printlist ();
PRIVATE:
T data [maxsize];
Int length;
};
# Endif
// Seq. cpp
# Include <iostream. h>
# Include "seq. H"
Template <class T>
Seqlist <t>: seqlist ()
...{
Length = 0;
}
Template <class T>
Seqlist <t>: seqlist (int A [], int N)
...{
If (n> maxsize) throw "error ";
For (INT I = 0; I <n; I ++)
Data [I] = A [I];
Length = N;
}
Template <class T>
Int seqlist <t >:: length ()
...{
Return length;
}
Template <class T>
Void seqlist <t>: insert (int I, T X)
...{
If (length> = maxsize)
Throw "Shangyi ";
If (I <1 | I> Length + 1)
Throw "weizhiyichang ";
For (Int J = length; j> = I; j --)
Data [J] = data [J-1];
Data [I-1] = X;
Length ++;
}
Template <class T>
T seqlist <t>: delete (int I)
...{
If (length = 0)
Throw "xiayi ";
If (I <1 | I> length)
Throw "weizhiyichang ";
X = data [I-1];
For (Int J = I; j <length; j ++)
Data [J-1] = data [J];
Length --;
Return X;
}
Template <class T>
T seqlist <t>: Get (int I)
...{
If (I <1 | I> length)
Throw "chazhaoweizhifeifa ";
Else
Return data [I-1];
}
Template <class T>
Int seqlist <t>: locate (t x)
...{
For (INT I = 0; I <length; I ++)
If (data [I] = X)
Return (I + 1 );
Return 0;
}
There are two points worth noting. The first is the preprocessing command in the header file. Sometimes, a complex project contains files containing other files, so that when a file is compiled, there is a risk that a header file will be re-read twice when two interfaces are called cyclically. To avoid this situation, each header file defines a symbol using the pre-processing command when reading the class interface. The first line of the header file checks whether the symbol is undefined. If yes, process the file. Otherwise, it will not be processed (skip to # endif ). Second, a class template is used in the header file. For a class declaration, you only need to define the class template once. To define a function in the source file, you must first define the class template instance Huawei class seqlist <t>. When defining each function, you must define the functions template.