我有以下代码片段:
A.h
include B.h
class A
{
public:
void createB();
B* getB();
private:
B *b;
};
A.cpp
void A::createB()
{
b = new B();
}
B* A::getB()
{
return b;
}
Main.cpp
int main()
{
int n = 3;
A *a_array = new A[n];
for ( int i = 0; i < n; i++ ) {
A *a = new A();
a_array[i] = *a;
}
for ( int i = 0; i < n; i++ ) {
A a = a_array[i];
a.createB();
}
a_array[0].doStuff(); // OK
a_array[0].getB(); // returns NULL
}
Output:
A created
A created
A created
B created
A destroyed
B created
A destroyed
B created
A destroyed
似乎 A 对象在循环中被破坏,但我可以在没有循环的情况下访问它们,但无法访问 A 的对象成员。