建立一个类模板Compare,用以比较同一类型的2个变量,包含构造方法、GetMax和GetMin成员方法。重新设计复数类Complex,使得Complex对象也适用于类模板Compare。编程实现一个队列的类模板。
时间: 2024-05-02 21:17:52 浏览: 12
```c++
#include<iostream>
using namespace std;
template <class T>
class Compare{
private:
T a,b;
public:
Compare(T _a, T _b){
a=_a;
b=_b;
}
T GetMax(){
return a>b?a:b;
}
T GetMin(){
return a<b?a:b;
}
};
template <class T>
class Complex{
private:
T real, imag;
public:
Complex(T _real, T _imag){
real=_real;
imag=_imag;
}
friend bool operator > (const Complex& c1, const Complex& c2){
return c1.real*c1.real+c1.imag*c1.imag>c2.real*c2.real+c2.imag*c2.imag;
}
friend bool operator < (const Complex& c1, const Complex& c2){
return c1.real*c1.real+c1.imag*c1.imag<c2.real*c2.real+c2.imag*c2.imag;
}
};
template <class T>
class Queue{
private:
T*data;
int front, rear, size;
public:
Queue(int _size){
data=new T[_size];
front=rear=0;
size=_size;
}
~Queue(){
delete[]data;
}
bool IsEmpty(){
return front==rear;
}
bool IsFull(){
return (rear+1)%size==front;
}
void Enqueue(T item){
if(IsFull()){
cout<<"Queue is full!"<<endl;
return;
}
data[rear]=item;
rear=(rear+1)%size;
}
T Dequeue(){
if(IsEmpty()){
cout<<"Queue is empty!"<<endl;
return T();
}
T item=data[front];
front=(front+1)%size;
return item;
}
};
int main(){
Compare<int> c1(1,2);
cout<<c1.GetMax()<<endl;
cout<<c1.GetMin()<<endl;
Complex<int> c2(1,2), c3(3,4);
Compare<Complex<int>> c4(c2,c3);
if(c2>c3){
cout<<"c2>c3"<<endl;
}
else{
cout<<"c2<=c3"<<endl;
}
if(c4.GetMax()==c3){
cout<<"Max is c3"<<endl;
}
Queue<int> q(5);
q.Enqueue(1);
q.Enqueue(2);
q.Enqueue(3);
q.Enqueue(4);
q.Enqueue(5);
q.Enqueue(6);
while(!q.IsEmpty()){
cout<<q.Dequeue()<<" ";
}
cout<<endl;
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)