#include <IOSTREAM>
using namespace std;
/*堆中對象數組、對象指針數組*/
class stu
{
public:
void set(int x){i = x + 6;}
int get(){return i*i;};
private:
int i;
};
void main()
{
const int n = 1000;
stu * p = new stu[n];//在堆中定義了一個對象數組,並將其首地址傳送給對象指針p.
int i;
stu * p0 = p;
for (i=0; i<n; i++)
{
p->set(i);
cout<<"p["<<i<<"]:"<<p->get()<<endl;
p++;
}
delete [] p0;//刪除堆中對象數組;(注:此處p0不可換為p,因為p的值在for循環中已被改變,不再是數組的首地址了。)
const int m = 1000;
stu * p1[m]; //p1成了指針數組的數組名,是個指針常量
for (i=0; i<m; i++)
{
p1[i] = new stu;//數組p1中,每個元素都是個對象指針,故可以直接被new stu賦值。
// p1 = p1+i;//錯誤,p1是個數組名,是個指針常量
p1[i]->set(i+1);
cout<<"p1["<<i<<"]:"<<p1[i]->get()<<endl;
delete p1[i];
}
}