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