马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
如题,代码如下。我想问的是hanoi类movein修改的是h的public变量,但为什么执行后a还是保持不变?#include <iostream>
#include <string.h>
#define Maxplates 10
using namespace std;
class hanoi
{
public:
int plates[Maxplates];
int num;
hanoi(){num = 0;};
hanoi(int j)
{
num = j;
for (int i = j; i >= 1; i--)
{
plates[j - i] = i;
}
};
void movein(hanoi h)
{
plates[num++] = h.plates[--h.num];
h.plates[h.num] = 0;
}
void show();
};
void hanoi::show()
{
if(num == 0)
{
return;
}
char coutchar;
int n, len;
for (int i = 0; i < num; i++)
{
n = plates[num - 1 - i]; //指针指向的盘子
len = ((plates[0] * 2 + 2) - 2 * n + 1) / 2;
for (int j = 0; j < len; j++)
{
cout << " ";
}
for (int j = 0; j < n; j++)
{
cout << "─";
}
cout << "┼";
for (int j = 0; j < n; j++)
{
cout << "─";
}
for (int j = 0; j < len; j++)
{
cout << " ";
}
cout << endl;
}
n = ((plates[0] * 2 + 2) / 2);
for (int j = 0; j < n; j++)
{
cout << "─";
}
cout << "┴";
for (int j = 0; j < n; j++)
{
cout << "─";
}
cout << endl;
}
int main()
{
cout << "请输入A柱上盘子总数:";
int num;
cin >> num;
if (num > Maxplates)
{
cout << "总数超出预算。";
return 0;
}
hanoi a(num), b;
cout << "A:" << endl;
a.show();
cout << "B:" << endl;
b.show();
b.movein(a);
cout << "A:" << endl;
a.show();
cout << "B:" << endl;
b.show();
}
控制台输出:请输入A柱上盘子总数:2
A:
─┼─
──┼──
───┴───
B:
A:
─┼─
──┼──
───┴───
B:
─┼─
──┴──
引用 #include <iostream>
#include <string.h>
#define Maxplates 10
using namespace std;
class hanoi
{
public:
int plates[Maxplates];
int num;
hanoi(){num = 0;};
hanoi(int j)
{
num = j;
for (int i = j; i >= 1; i--)
{
plates[j - i] = i;
}
};
//void movein(hanoi h)
void movein(hanoi &h)
{
plates[num++] = h.plates[--h.num];
h.plates[h.num] = 0;
}
void show();
};
void hanoi::show()
{
if(num == 0)
{
return;
}
char coutchar;
int n, len;
for (int i = 0; i < num; i++)
{
n = plates[num - 1 - i]; //指针指向的盘子
len = ((plates[0] * 2 + 2) - 2 * n + 1) / 2;
for (int j = 0; j < len; j++)
{
cout << " ";
}
for (int j = 0; j < n; j++)
{
cout << "─";
}
cout << "┼";
for (int j = 0; j < n; j++)
{
cout << "─";
}
for (int j = 0; j < len; j++)
{
cout << " ";
}
cout << endl;
}
n = ((plates[0] * 2 + 2) / 2);
for (int j = 0; j < n; j++)
{
cout << "─";
}
cout << "┴";
for (int j = 0; j < n; j++)
{
cout << "─";
}
cout << endl;
}
int main()
{
cout << "请输入A柱上盘子总数:";
int num;
cin >> num;
if (num > Maxplates)
{
cout << "总数超出预算。";
return 0;
}
hanoi a(num), b;
cout << "A:" << endl;
a.show();
cout << "B:" << endl;
b.show();
b.movein(a);
cout << "A:" << endl;
a.show();
cout << "B:" << endl;
b.show();
}
|