类与指针

析构函数构造的两种方法:

range::range (float a ,float b,float c){width=a,length=b,hight=c;
 cout<<"构数成功造函"<<endl;}  

这种方法写出时,函数内部的顺序没有关系。

2、

range::range(float a,float b,float c)
	{width=a,length=b,hight=c,cout<<"构造析构函数成功"<<endl;}  

eg:

class  A
{ public :   // 构造和析构必须public
       A( ) { cout<<"构造 A()"<< endl;   }
     ~A( ) { cout<<"析构~A()"<< endl; }
};
class  B
{ public : 
       B( ) { cout<<"构造 B()"<<endl; }
     ~B( ) { cout<<"析构~B()"<<endl; }
};  

构造函数遵从:先构造,后析构
后构造,先析构


构造对象数组:

  • 每个元素都是一个对象
  • 数组有多少个对象就调用多少次构造函数

代码块:

class range
{
	float width;
	float length;
	float hight;
	float area;
	int x;
public:  

range::range(float a,float b,float c)
	{width=a,length=b,hight=c,cout<<"构造析构函数成功"<<endl;}
	void get_x(int a){this->x=a;}  
float range::getarea(void)
	{return width*length*hight;}  
}  
int main()
{
	range data[3]={range(2,3,4),range(5,6,7),range(22,2,2)};
	for(int i=0;i<3;i++)
		cout<<"数组"<<i+1<<"的面积:"<<data[i].getarea()<<endl;
	//point point1,point2;  
system("pause");
return 0;
}  

运行的结果:

构造析构函数成功
构造析构函数成功
构造析构函数成功
数组1的面积:24
数组2的面积:210
数组3的面积:88
请按任意键继续. . .


对象指针与数组:

class point
{
	int x,y;
	static int count;
public:
	void set_data(int a,int b){x=a,y=b;}
	void display(void)
	{
		cout<<"x="<<x<<"  "<<"y="<<y<<endl;
	}
};
int main()
{
	point a[5];
	point *p[5];
	for(int i=0;i<5;i++)
	{
		p[i]=&a[i];
		p[i]->set_data(i,i+2);
		//a[i].set_data(i,i+2);
		p[i]->display();
		(*p)++;
	}
system("pause");
return 0;
}
原文地址:https://www.cnblogs.com/lixianhu1998/p/11919637.html