编辑:在二维结构的情况下(你说你知道你的二维结构需要多大,所以我们假设循环中的 10 是你想要的二维数组的大小。
#include <iostream>
#include <vector>
using namespace std;
class Bar {
public:
int BarInfo;
};
class Foo {
public:
Foo() {
// Allocates 10 vector spots for 10 bar elements - 100 bars, 10 x 10
for (int i = 0; i < 10; i++) {
// Puts 10 bars pointer at the end;
// Heap-allocated (dynamically), which
// means it survives until you delete it
// The [10] is array syntax, meaning you'll have 10 bars
// for each bars[index] and then
// you can access it by bars[index][0-9]
// If you need it to be more dynamic
// then you should try vector<vector<Bar>>
bars.push_back(new Bar[10]);
}
}
Bar* operator[] (int index) {
return bars[index];
}
~Foo () {
// Cleanup, because you have pointers inside the vector,
// Must be done one at a time for each element
for (int i = 0; i < bars.size(); i++) {
// TODO: how to clean up bars properly?
// Each spot in the vector<> contains 10 bars,
// so you use the array deletion
// and not just regular 'delete'
delete[] bars[i]; // deletes the 10 array elements
}
}
private:
// vector might not be a bad idea.
vector<Bar*> bars;
};
这是我用于测试编写的代码的主要方法,它的工作方式就像你认为二维数组应该工作一样:
int main ( int argc, char* argv[] ) {
Foo foo;
// Bar at 1st row, 2nd column ( row index 0, column index 1 )
// Bar& is a reference
Bar& bar12 = foo[0][1];
bar12.BarInfo = 25;
int stuffInsideBar = foo[0][1].BarInfo; // 25
return 0;
}
我希望这有助于并使您更接近您正在做的事情。我在这里使用了一种技术,它可能会超越初学者的头脑,以使Foo
该类的行为就像您认为的 2D 数组一样。这称为运算符重载。它是 C++ 中的一项强大功能,因此一旦您掌握了更多基础知识,它可能对您未来的项目或当前项目有用。祝你好运!
~~~~~~~~~~~~~~~~~~~~~~~
编辑前的旧答案
~~~~~~~~~~~~~~~~~~~~~~~
看来您做的间接太多了。虽然另一个人的回答向您展示了如何清理您已经设法做的事情,但我认为您可以从改变您处理课程的方式中受益。
#include <iostream>
#include <vector>
using namespace std;
class Bar {};
class Foo {
public:
Foo() : bars() {
// bars is no longer a pointer-to-vectors, so you can just
// allocate it in the constructor - see bars() after Foo()
//bars = new vector<Bar>();
for (int i = 0; i < 10; i++) {
// Puts 1 bar pointer at the end;
// Heap-allocated (dynamically), which
// means it survives until you delete it
bars.push_back(new Bar());
}
}
~Foo () {
// Cleanup, because you have pointers inside the vector,
// Must be done one at a time for each element
for (int i = 0; i < 10; i++) {
// TODO: how to clean up bars properly?
// TODOING: One at a time
delete bars[i]; // deletes pointer at i
}
}
private:
// You don't need to ** the vector<>,
// because it's inside the class and
// will survive for as long as the class does
// This vector will also be copied to copies of Foo,
// but the pointers will remain the same at the time
// of copying.
// Keep in mind, if you want to share the vector, than
// making it a std::shared_ptr of a
// vector might not be a bad idea.
vector<Bar*> bars;
};
如果您通过引用将类传递给函数,vector<Bar*>
则类内部不会复制自身或删除自身,从而使其在单个堆栈帧之后持续存在。
在您的main
中,这应该正确清理,并且比 vector** 更容易跟踪。但是,如果由于某种原因需要矢量**,那么 home_monkey 的答案应该可以帮助您更多。