[英]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.