C++實現
using namespace std;
typedef char ElemType;
class Triplet
{
public:
Triplet(ElemType v1,ElemType v2,ElemType v3);
~Triplet();
ElemType Get(int) const;
void Put(int,ElemType);
bool IsAscending() const;
bool IsDescending() const;
ElemType Min() const;
ElemType Max() const;
private:
ElemType *T;
};
Triplet::Triplet(ElemType e1,ElemType e2,ElemType e3)
{
cout<<"In the Triplet Constructor"<<endl;
T=new ElemType[3];
T[0]=e1;
T[1]=e2;
T[2]=e3;
}
Triplet::~Triplet()
{
cout<<"In the Triplet Destructor"<<endl;
delete [] T;
}
ElemType Triplet::Get(int i) const
{
if (i<1||i>3) throw i;
return T[i-1];
}
void Triplet::Put(int i,ElemType e)
{
if (i<1||i>3) throw i;
T[i-1]=e;
}
bool Triplet::IsAscending() const
{
return (T[0]<=T[1])&&(T[1]<=T[2]);
}
bool Triplet::IsDescending() const
{
return (T[0]>=T[1])&&(T[1]>=T[2]);
}
ElemType Triplet::Min() const
{
return T[0]<=T[1]?(T[0]<=T[2]?T[0]:T[2]):(T[1]<=T[2]?T[1]:T[2]);
}
ElemType Triplet::Max() const
{
return T[0]>=T[1]?(T[0]>=T[2]?T[0]:T[2]):(T[1]>=T[2]?T[1]:T[2]);
}
ostream&operator<<(ostream&output,const Triplet&T)
{
output<<"Triplet:["<<T.Get(1)<<","<<T.Get(2)<<","<<T.Get(3)<<"]"<<endl;
return output;
}
int main()
{
Triplet T1('A','B','C');
try
{
cout<<T1;
cout<<"Elem 1:"<<T1.Get(1)<<endl;
cout<<"Elem 2:"<<T1.Get(2)<<endl;
cout<<"Elem 3:"<<T1.Get(3)<<endl;
T1.Put(3,'D');
cout<<T1;
cout<<"IsAscending:"<<T1.IsAscending()<<endl;
cout<<"IsDescending:"<<T1.IsDescending()<<endl;
cout<<"Min Elem:"<<T1.Min()<<endl;
cout<<"Max Elem:"<<T1.Max()<<endl;
T1.Put(4,'M');
}
catch(int)
{
cout<<"Error:Triplet Access Overflow"<<endl;
}
return 0;
}