c++入门问题

来源:百度知道 编辑:UC知道 时间:2024/05/30 06:59:48
#include<iostream.h>
class CPoint
{
int x,y;
public:
CPoint (int x0,int y0=0)
{ x=x0; y=y0; }
CPoint ()
{ x=0;y=0; }
void init(int x0=0,int y0=0)
{x=x0; y=y0;}
void print()
{ cout<<x<<" "<<y<<endl; }
};
void main()
{
CPoint *ptr = new CPoint[5]; /*为对象动态申请存储空间。
这句是怎么工作的?会调用构造函数吗?
怎么调用?ptr怎么变成对象数组了?*/
int x,y;
if(!ptr)
{
cout<<" allocation failure \n";
return;
}
cout<<" 请输入数据\n";
for (int k=0;k<5;k++,ptr++) /* 和for (int k=0;k<5;k++;ptr++) 有什么区别呀!*/
{
cin >> x >>y;
ptr->init(x,y); /*把接收到的数据赋给成员怎么处理的?*/
}
cout<<"\n 输入数据 \n";
for (k=0;k<5;k++)
(--ptr)->print(); //ptr 是指针数组吗,可以这样用!
delete []ptr;
return;
}

不好意思,我弄错了,new函数还是会调用默认构造函数的。特此更正

CPoint *ptr = new CPoint[5];//分配5个足够容纳Cpoint类型的内存,把第一个Cpoint的地址赋值给ptr;会调用默认构造函数,创建的是占用5个空对象的空内存;ptr并不是对象数组,而是指向Cpoint[0]的指针,cpt本身占用4个内存,*ptr才占用sizeof(Cpoint)个内存

for (int k=0;k<5;k++,ptr++) // 和for (int k=0;k<5;k++;ptr++) 的区别在于前面前者符合for语句for(;;)的语法,后者for(;;;)没有这个用法,错的

ptr->init(x,y); //把接收到的数据赋给成员赋值给当前指针指向的对象的数据成员,和(*ptr).init(x,y)等价。

(--ptr)->print(); //ptr 是指针数组,--ptr指向Cpoint[5],该循环从后向前输出Cpoint[k].x和Cpoint[k].y