[英]Reference to vector as class member
我试图通过引用将向量作为 class 成员传递,但我似乎已经通过值传递了它。
所以我正在制作一个 class,它有一个 function,它可以改变向量中元素的 position。 代码看起来像这样。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Example {
int x, y;
vector<vector<string>> chart;
public:
Example(int i, int j, vector<vector<string>>& arr);
void Swap_up();
};
Example::Example(int i, int j, vector<vector<string>>& arr) :x(i), y(j), chart(arr) {
}
void Example::Swap_up() {
if (x - 1 >= 0 && chart[x - 1][y].at(0) == ' ') {
string temp = chart[x-1][y];
chart[x - 1][y] = chart[x][y];
chart[x][y] = temp;
x = y - 1;
for (int i = 0; i < chart.size(); i++) {
for (int j = 0; j < chart[0].size(); j++) {
cout << '[' << chart[i][j] << ']';
}
cout << endl;
}
cout << endl;
}
else
cout << "Invalid move" << endl;
}
int main() {
int chart_height;
int chart_width;
cout << "Enter height of the chart in number of spaces (Minimum number of spaces is 7)" << endl;
cin >> chart_height;
cout << "Enter width of the chart in number of spaces (Minimum number of spaces is 7)" << endl;
cin >> chart_width;
vector<vector<string>> chart;
chart.resize(chart_height);
for (int i = 0; i < chart_height; i++)
chart[i].resize(chart_width);
for (int i = 0; i < chart_height; i++) {
for (int j = 0; j < chart_width; j++) {
if (chart[i][j] == "")
chart[i][j].insert(0, 3, ' ');
}
}
chart[6][5] = "EXA";
for (int i = 0; i < chart_height; i++) {
for (int j = 0; j < chart_width; j++) {
cout << '[' << chart[i][j] << ']';
}
cout << endl;
}
cout << endl;
Example Exa1(6, 5, chart);
Exa1.Swap_up();
for (int i = 0; i < chart_height; i++) {
for (int j = 0; j < chart_width; j++) {
cout << '[' << chart[i][j] << ']';
}
cout << endl;
}
chart.clear();
chart.resize(0);
return 0;
}
我以为我使用了对向量的引用作为我的 class 的成员。所以我让程序打印图表,其中包含原始 position 中的元素,然后执行 swap_up,因此 class 方法将元素向上移动一个空格并打印再次图表。 这奏效了。
问题是,然后我让程序第三次打印图表,元素又回到了原来的 position。所以我显然通过值而不是通过引用将向量作为 class 成员传递,所以 class 方法实际上并没有更改图表但它的副本。 我做错了什么?
我以为我使用了对向量的引用作为我的 class 的属性。
不。您将对向量的引用作为参数传递给类的构造函数。 这就是你所做的一切。
您的构造函数将其分配给其 class 成员。 在讨论 C++ 时使用正确的术语非常重要。C++ 足够复杂,因此不一致的术语常常导致混淆。
vector<vector<string>> chart;
这是一个通常描述为 class 的成员,而不是“属性”。
如您所见,它不是参考。 它是一个离散的object。这意味着当构造函数初始化class成员时
... chart(arr)
引用的向量被复制到chart
中,一个离散的 object。
对chart
的后续更改对通过引用传递给构造函数的向量没有影响。 毕竟,为什么要这样做? 它是一个向量,有其自身的优点。
如果您的期望是原始向量应该受到影响,那么 class 成员本身应该是一个参考:
class Example {
int x, y;
vector<vector<string>> &chart;
然后, chart
引用从对传递给构造函数的参数的引用进行初始化,随后对chart
引用该向量的更改。
这种设计通常由于其他原因而存在问题,但它们对问题无关紧要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.