0
#include <iostream>
class MyClass
{
public:
MyClass() {
itsAge = 1;
itsWeight = 5;
}
~MyClass() {}
int GetAge() const { return itsAge; }
int GetWeight() const { return itsWeight; }
void SetAge(int age) { itsAge = age; }
private:
int itsAge;
int itsWeight;
};
int main()
{
MyClass * myObject[50]; // define array of objects...define the type as the object
int i;
MyClass * objectPointer;
for (i = 0; i < 50; i++)
{
objectPointer = new MyClass;
objectPointer->SetAge(2*i + 1);
myObject[i] = objectPointer;
}
for (i = 0; i < 50; i++)
std::cout << "#" << i + 1 << ": " << myObject[i]->GetAge() << std::endl;
for (i = 0; i < 50; i++)
{
delete myObject[i];
myObject[i] = NULL;
}
我想知道爲什麼objectPointer必須在for循環中,如果我將它取出並放在for循環之前,我會得到無意義的結果。幫助將不勝感激,謝謝...抱歉可怕的格式。對象的動態內存分配
你的意思是你會得到無意義的結果,因爲它現在是?你在'for'循環之前定義'objectPointer'。 – 2013-04-05 16:14:10
@sftrabbit他顯然意味着assigment'objectPointer = new MyClass;' – Paranaix 2013-04-05 16:22:04