私はC++言語の知識を向上させようとしており、スタックのスタックを作成しています。以下は私の質問の非常に短い例です:それを行うために関数を使うのではなく、構造体のメンバーに直接アクセスしなければならないのはなぜですか?どうしてこのようなことが起こったのか分かっている人は、非常に感謝しています!C++の構造体の動作
stacks.stacks[0]
はそれへの参照を返しながらおかげ
#include <iostream>
#include <vector>
using namespace std;
struct Stack {
int N;
vector<int> stack;
int len() { return stack.size(); }
void add(int N) { stack.push_back(N); }
};
struct Stacks {
vector<Stack> stacks;
Stack getStackAtIndex(int i) { return stacks[i]; }
void addStack(Stack stack) { stacks.push_back(stack); }
void printStacks() {
cout << "Printing stacks" << endl;
for (int i = 0; i < stacks.size(); i++) {
cout << "Stack #" << i << ": ";
for (int j = 0; j < stacks[i].len(); j++) {
cout << stacks[i].stack[j];
if (j != stacks[i].len()-1) cout << " -> ";
}
cout << endl;
}
}
};
int main() {
Stacks stacks;
Stack stack;
stack.add(1);
stacks.addStack(stack);
// This does not work:
// stacks.getStackAtIndex(0).add(2);
// This works:
stacks.stacks[0].stack.push_back(2);
stacks.printStacks();
return 0;
}
getStackAtIndexが参照を返している可能性がありますか? – Max
[参照を返すとはどういう意味ですか?](https://stackoverflow.com/questions/13718465/what-does-it-mean-to-return-a-reference) – AndyG