/*
对象指针:
对象指针就是一个类的对象的地址。
一般声明格式:
类名 *对象指针名;
或:
类名 *对象指针名=new 类名;
*/
#include <iostream>
class Date //定义Date类
{
private : //声明私有数据成员
int year,month,day;
public: //声明公有
void set(int year, int month, int day);
bool fun();
void show();
};
//Date 类中成员函数的实现(可以使用默认值)
void Date::set(int _year, int _month, int _day)
{
year=_year;
month=_month;
day=_day;
}
bool Date::fun()
{
if ((year%4==0&&year%100!=0)||(year%400==0)) {
return true;
}
else
return false;
}
void Date::show()
{
std::cout<<year<<"-"<<month<<"-"<<day<<std::endl;
}
int main(int argc, const char * argv[])
{
Date myDate; //声明Date类的对象
Date *p; //声明指向Date类对象的指针
p=&myDate; //将myDate的地址赋给p
p->set(2013, 11, 01);
p->show();//2013-11-1
(*p).set(2013, 11, 18);
(*p).show();//2013-11-18
myDate.show();//2013-11-18
return 0;
}
this指针
/*
this 指针
this 指针是一个隐含于每个类的成员函数之中的特殊指针,每个成员函数都有一个this指针变量。
*/
#include <iostream>
class Date //定义Date类
{
public: //声明公有数据成员和属性
int year,month,day;
Date(int _year,int _month,int _day);//声明构造函数
void show();
};
Date::Date(int _year,int _month,int _day)
{
year=_year;
month=_month;
day=_day;
}
void display(Date *pDate)
{
std::cout<<pDate->year<<"-"<<pDate->month<<"-"<<pDate->day<<std::endl;
}
void Date::show()
{
//第一种输出
std::cout<<this->year<<"-"<<this->month<<"-"<<this->day<<std::endl;
//第二种输出
display(this);
}
int main(int argc, const char * argv[])
{
Date myDate(2013,11,18);
myDate.show();
}