c/c++语言开发共享C++对象指针数组与堆中对象数组

#include <iostream> using namespace std; /*堆中对象数组、对象指针数组*/ class stu { public: void

  #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];  	}    }

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/607730.html

(0)
上一篇 2021年5月14日
下一篇 2021年5月14日

精彩推荐