类外修改public变量值问题
如题,代码如下。我想问的是hanoi类movein修改的是h的public变量,但为什么执行后a还是保持不变?#include <iostream>
#include <string.h>
#define Maxplates 10
using namespace std;
class hanoi
{
public:
int plates;
int num;
hanoi(){num = 0;};
hanoi(int j)
{
num = j;
for (int i = j; i >= 1; i--)
{
plates = i;
}
};
void movein(hanoi h)
{
plates = h.plates[--h.num];
h.plates = 0;
}
void show();
};
void hanoi::show()
{
if(num == 0)
{
return;
}
char coutchar;
int n, len;
for (int i = 0; i < num; i++)
{
n = plates; //指针指向的盘子
len = ((plates * 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 * 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:
─┼─
──┴──
控制台输出有点变形,图片:
https://z3.ax1x.com/2021/07/16/WQEpFA.png 引用
#include <iostream>
#include <string.h>
#define Maxplates 10
using namespace std;
class hanoi
{
public:
int plates;
int num;
hanoi(){num = 0;};
hanoi(int j)
{
num = j;
for (int i = j; i >= 1; i--)
{
plates = i;
}
};
//void movein(hanoi h)
void movein(hanoi &h)
{
plates = h.plates[--h.num];
h.plates = 0;
}
void show();
};
void hanoi::show()
{
if(num == 0)
{
return;
}
char coutchar;
int n, len;
for (int i = 0; i < num; i++)
{
n = plates; //指针指向的盘子
len = ((plates * 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 * 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();
}
页:
[1]