指针与对象,指针与对象数组的联系与区别
程序员文章站
2024-03-25 20:21:58
...
#include <iostream>
using namespace std;
class Recta{
public:
Recta(int len=10,int wid=10)
{
length=len;
width=wid;
}
int getArea()
{
return (length*width);
}
void disp()
{
cout<<"长是:"<<length<<" "<<"高是:"<<width<<endl;
cout<<"面积:"<<getArea()<<endl;//rec[i].getArea() 是错的,类是整体,不知道主函数里有什么
}
private:
int length,width;
};
int main()
{
Recta rec[3]={
Recta(15,20),
Recta(5,6),
Recta(30,40)
};
for(int i=0;i<3;i++)
{
rec[i].disp();
}
return 0;
}
//=====================================================================================
#include <iostream>
using namespace std;
class Date{
public:
Date(int y,int m,int d);
void setDate(int y,int m,int d);
void show();
private:
int year;
int month;
int day;
};
Date::Date(int y,int m,int d)
{
year=y;
month=m;
day=d;
}
inline void Date::setDate(int y,int m,int d)
{
year=y;
month=m;
day=d;
}
void Date::show()
{
cout<<year<<"."<<month<<"."<<day<<endl;
}
int main()
{
Date date(2013,2,25);
date.show();
Date *dp;
dp=&date; //这的date是对象,不是指针,所以要用取地址符
dp->setDate(2012,11,16);
dp->show();
return 0;
}
//=============================================================
#include <iostream>
using namespace std;
class Date{
public:
Date(int y=2012,int m=7,int d=20);
void setDate(int y,int m,int d);
void show();
private:
int year;
int month;
int day;
};
Date::Date(int y,int m,int d)
{
year=y;
month=m;
day=d;
}
inline void Date::setDate(int y,int m,int d)
{
year=y;
month=m;
day=d;
}
void Date::show()
{
cout<<year<<"."<<month<<"."<<day<<endl;
}
int main()
{
Date date[2];
Date *dp;
date[0].setDate(2012,11,16);
date[1].setDate(2013,2,25);
dp=date; //date[]是对象数组,date是起始地址,即指针,所以不用取地址符号。当把对象数组中的第i个赋给指针时,则用dp=&date[i]
dp->show();
dp++;
dp->show();
return 0;
}
上一篇: Cocos2dx <基础> 精灵
下一篇: Cocos2dx <基础> 帧动画