X的放大与缩小(运算符重载)
题目描述
X字母可以放大和缩小,变为n行X(n=1,3,5,7,9,…,21)。例如,3行x图案如下:
现假设一个n行(n>0,奇数)X图案,遥控器可以控制X图案的放大与缩小。遥控器有5个按键,1)show,显示当前X图案;2)show++, 显示当前X图案,再放大图案,n+2;3)++show,先放大图案,n+2,再显示图案;4)show–,显示当前X图案,再缩小图案,n-2;5)–show,先缩小图案,n-2,再显示图案。假设X图案的放大和缩小在1-21之间。n=1时,缩小不起作用,n=21时,放大不起作用。
用类CXGraph表示X图案及其放大、缩小、显示。主函数模拟遥控器,代码如下,不可修改。请补充CXGraph类的定义和实现。
输入
第一行n,大于0的奇数,X图案的初始大小。
第二行,操作次数
每个操作一行,为show、show++、show–、--show、++show之一,具体操作含义见题目。
输出
对每个操作,输出对应的X图案。
示例输入
3
5
show
show++
show++
++show
–show
示例输出
XXX
X
XXX
XXX
X
XXX
XXXXX
XXX
X
XXX
XXXXX
XXXXXXXXX
XXXXXXX
XXXXX
XXX
X
XXX
XXXXX
XXXXXXX
XXXXXXXXX
XXXXXXX
XXXXX
XXX
X
XXX
XXXXX
XXXXXXX
#include<iostream>
using namespace std;
class CXGraph{
public:
CXGraph(){
}
CXGraph(int n1)
{
n=n1;
}
CXGraph(const CXGraph &a)
{
n=a.n;
}
friend CXGraph operator ++ (CXGraph &a);
friend CXGraph operator ++ (CXGraph &a,int);
friend CXGraph operator -- (CXGraph &a);
friend CXGraph operator -- (CXGraph &a,int);
friend ostream &operator << (ostream &,CXGraph const &a);
//返回的是临时的对象,临时对象不能作为引用传入,加了const相当于一个值
private:
int n;
};
CXGraph operator ++ (CXGraph &a)
{
if(a.n!=21)
{
a.n++;
a.n++;
}
return a;
}
CXGraph operator ++ (CXGraph &a,int)
{
CXGraph c=a;
if(a.n!=21)
{
a.n++;
a.n++;
}
return c;
}
CXGraph operator -- (CXGraph &a)
{
if(a.n!=1)
{
a.n--;
a.n--;
}
return a;
}
CXGraph operator -- (CXGraph &a,int)
{
CXGraph c=a;
if(a.n!=1)
{
a.n--;
a.n--;
}
return c;
}
ostream & operator << (ostream & output,CXGraph const &a)
{
int i,j,k=a.n;
for(i=0;i<(a.n+1)/2;i++)
{
for(j=0;j<(a.n-k)/2;j++)
output<<" ";
for(j=k;j>0;j--)
output<<"X";
output<<endl;
k=k-2;
}
k=3;
for(i=(a.n+1)/2;i<a.n;i++)
{
for(j=(a.n-k)/2;j>0;j--)
output<<" ";
for(j=0;j<k;j++)
output<<"X";
output<<endl;
k=k+2;
}
return output;
}
int main()
{
int t,n;
string command;
cin>>n;
CXGraph xGraph(n);
cin>>t;
while(t--)
{
cin>>command;
if(command=="show++")
cout<<xGraph++<<endl;
else if(command=="++show")
cout<<++xGraph<<endl;
else if(command=="show--")
cout<<xGraph--<<endl;
else if(command=="--show")
cout<<--xGraph<<endl;
else if(command=="show")
cout<<xGraph<<endl;
}
return 0;
}